#@gmic
#
#  File        : gmic_def.gmic
#                ( G'MIC default custom commands )
#
#  Description : Define recognized commands for the G'MIC interpreter
#                and available filters for GIMP plug-in.
#                ( http://gmic.sourceforge.net )
#
#                This file is also a part of the CImg Library project.
#                ( http://cimg.sourceforge.net )
#
#  Location    : If you are using the G'MIC plug-in for GIMP, and made
#                a filter refresh via Internet, then a copy of this file
#                should be found in the folder :
#
#                  $HOME/.gmic_def.xxxx    (on Unix-based OS).
#                  %APPDATA/gmic_def.xxxx  (on Windows-based OS).
#
#  Usage       : gmic [-m gmic_def.gmic] (...)
#
#  Copyright   : David Tschumperle
#                ( http://www.greyc.ensicaen.fr/~dtschump/ )
#
#  License     : CeCILL v2.0
#                ( http://www.cecill.info/licences/Licence_CeCILL_V2-en.html )
#
#  This software is governed by the CeCILL  license under French law and
#  abiding by the rules of distribution of free software.  You can  use,
#  modify and/ or redistribute the software under the terms of the CeCILL
#  license as circulated by CEA, CNRS and INRIA at the following URL
#  "http://www.cecill.info".
#
#  As a counterpart to the access to the source code and  rights to copy,
#  modify and redistribute granted by the license, users are provided only
#  with a limited warranty  and the software's author,  the holder of the
#  economic rights,  and the successive licensors  have only  limited
#  liability.
#
#  In this respect, the user's attention is drawn to the risks associated
#  with loading,  using,  modifying and/or developing or reproducing the
#  software by the user in light of its specific status of free software,
#  that may mean  that it is complicated to manipulate,  and  that  also
#  therefore means  that it is reserved for developers  and  experienced
#  professionals having in-depth computer knowledge. Users are therefore
#  encouraged to load and test the software's suitability as regards their
#  requirements in conditions enabling the security of their systems and/or
#  data to be ensured and,  more generally, to use and operate it in the
#  same conditions as regards security.
#
#  The fact that you are presently reading this means that you have had
#  knowledge of the CeCILL license and that you accept its terms.
#

#------ Syntax rules for a G'MIC command file :
#
#*** General syntax :
#
# - Each line starting with 'command_name :' starts a new G'MIC custom command definition.
# - Each line starting with '#' is a comment line.
# - Any other line is considered as the continuation of a previously started G'MIC custom command.
#
#*** Rules for 'gmic' (command-line interpreter) :
#
# - A comment line starting with '#@gmic' will be parsed by 'gmic' in order to display help for
#    G'MIC custom commands (when invoked with option '-h'). More precisely :
#
#      _ '#@gmic :: section' puts a new section separator in the displayed help.
#      _ '#@gmic command : arguments : description' starts a new command description
#      _ '#@gmic : description' add a new line to the last command description.
#
#*** Rules for 'gmic_gimp' (plug-in for GIMP) :
#
# - A comment line starting with '#@gimp' will be parsed by the GIMP plug-in to define the filter tree.
# - A comment line starting with '#@gimp_xx' will define a filter only for a specific language 'xx'
#    (e.g. 'en','fr'...).
# - More precisely, the syntax of a '#@gimp' comment line is be :
#
#    '#@gimp Folder name'
#
# or
#
#    '#@gimp Command name : command, preview_command, parameter = typedef, parameter2 = typedef'
#    '#@gimp : parameter3 = typedef, parameter4 = typedef ...., parameterN = typedef'
#
#   where :
#
#      'command' is the G'MIC command name called to process the image.
#
#      'preview_command' is the G'MIC command name called to process the preview.
#
#           Note that you can optionally specify a float-valued factor>=0 between parentheses at the end of
#           the 'preview_command' to force the default zoom factor used by the GIMP preview for this filter.
#           Use (0) for a 1:1 preview, (1) for previewing the whole image, (2) for 1/2 image and so on...
#
#      'parameter = typedef' tells about the names, types and default values of the filter parameters.
#
#           'typedef' can be :
#
#      _ 'float(default_value,min_value,max_value)'       : Add a float-valued parameter (as a GUI float slider).
#      _ 'int(default_value,min_value,max_value)'         : Add a integer parameter (as a GUI integer slider).
#      _ 'bool(default_value={ 0 | 1 | false | true })'   : Add a boolean parameter (0 or 1) (as a GUI checkbutton).
#      _ 'choice(_default_indice,Choice0,..,ChoiceN)'     : Add a integer parameter (as a GUI combobox).
#      _ 'text(_is_multiline={ 0 | 1 },_default text)'    : Add a single or multi-line text parameter (as a GUI text entry).
#      _ 'file(_default_filename)'                        : Add a filename parameter (as a GUI filechooser).
#      _ 'folder(_default_foldername)'                    : Add a foldername parameter (as a GUI folderchooser).
#      _ 'color(defaultR,defaultG,defaultB,_defaultA)'    : Add R,G,B[,A] parameters (as a GUI colorchooser).
#      _ 'note(_label)'                                   : Display a label, but do not add a new parameter.
#      _ 'link(_alignement,_label,URL)'                   : Display a label that link to a specified URL.
#      _ 'separator()'                                    : Display an horizontal separator.
#
#   Type separators '()' can be replaced by '[]' or '{}' if necessary (for instance if parentheses are required in
#   an argument of the typedef, e.g in a text). You can also replace 'typedef' by '_typedef' to tell the plug-in not
#   to update the image preview when the corresponding parameter is modified.
#
#   Use '_none_' as a special command or preview_command to tell the plug-in that the entry requires no G'MIC call.
#
#-----------------------------------------------------------------------------------------------------------------------

#---------------------------------
#
#@gmic :: Inputs / outputs
#
#---------------------------------

#@gmic apply_camera : _command,_camera_index>=-1,_skip_frames>=0,_output_filename
#@gmic : Apply specified command on live camera stream, and display it on display window [0].
#@gmic : Default values : 'command=""', 'camera_index=-1','skip_frames=0' and 'filename=""'.
apply_camera : -skip "${1=},${4=}" -check "${2=-1}>=-1 && ${3=0}>=0"
  -v - -if {$2==-1} stream=\#default -else stream=\#$2 -endif
  -v + -e[^-1] "Apply command '$1' on camera stream "$stream", with $3 frames skip and filename '$4'." -v -
  -l[] frame=0 -do
    -camera $2,1,$3 $1 -w[-1] -1,-1,-1,-1,"(Camera "$stream", "{w}x{h}")"
    -if {narg("$4")} -o[-1] @{"-filename \"$4\","$frame} frame={$frame+1} -endif
    -if @{!,S} -o[-1] gmic_camera.png -endif
    -if {(@{!,CTRLLEFT}" || "@{!,CTRLRIGHT})" && "@{!,D}} -w[] {@{!,w}*1.5},{@{!,h}*1.5} -wait -1 -endif # Increase window size.
    -if {(@{!,CTRLLEFT}" || "@{!,CTRLRIGHT})" && "@{!,C}} -w[] {@{!,w}/1.5},{@{!,h}/1.5} -wait -1 -endif # Decrease window size.
    -if {(@{!,CTRLLEFT}" || "@{!,CTRLRIGHT})" && "@{!,R}} -w[] @{0,w},@{0,h} -wait -1 -endif             # Reset window size.
    -rm[-1]
  -while {@!" && "!@{!,ESC}" && "!@{!,Q}} -endl -v +

#@gmic d0 : eq. to '-display0'.
d0 :
 -_display0

#@gmic display0
#@gmic : Display selected images without value normalization.
#@gmic : (eq. to '-d0').
display0 :
  -_display0

_display0 :
  -v -
  w=0 h=0 d=0 s=0
  -repeat @# w={$w+w} h={max($h,h)} d={max($d,d)} s={max($s,s)} -mv[-1] 0 -done
  -if {@#==1} -w -1,-1,0,0,@{0,n}\ ($wx$hx$dx$s)
  -elif {@#==2} -w -1,-1,0,0,@{0,n},@{-1,n}\ ($wx$hx$dx$s)
  -else -w -1,-1,0,0,@{0,n},..,@{-1,n}\ ($wx$hx$dx$s)
  -endif
  -v + -d
  -v - -w[] 0 -v +

#@gmic da : eq. to '-display_array'.
da :
  -_display_array $*

#@gmic display_array : _width>0,_height>0
#@gmic : Display images in interactive windows where pixel neighborhoods can be explored.
#@gmic : Default values : 'width=13' and 'height=width'.
display_array :
  -_display_array $*

_display_array : -check ${1=13}>0" && "${2=$1}>0
  -e[0--3] "Display $1x$2 array of pixel values for image$?."
  -v -
  dxb={round($1/2,1,1)} dxf={$1-1-$dxb}
  dyb={round($2/2,1,1)} dyf={$2-1-$dyb}

  -repeat @# -l[$>]

    # Manage cases of small and large images.
    -if {w<128" && "h<128}
      -r[-1] 128,128,100%,100%,0,0,0.5,0.5
    -endif
    x0=0 y0=0 w={w} h={h}
    wmax={0.9*@{!,u}} hmax={0.9*@{!,v}}
    -do
      -if {w>=$wmax||h>=$hmax}
        n=@{-1,n} -nm[-1] "Image "'@{-1,b}.@{-1,x}'" is too large, please select a sub-image."
        --select[-1] 2 x0={i(0,0)} y0={i(0,1)} w={1+i(0,3)-i(0,0)} h={1+i(0,4)-i(0,1)}
        -rm[-1] -nm[-1] $n
      -endif
      --z[-1] $x0,$y0,0,{$x0+$w-1},{$y0+$h-1},0 -round[-1] 1 -n[-1] 0,255
    -while {w>=$wmax||h>=$hmax}

    x1=-1 y1=-1 c1=0 ox1=-1 oy1=-1 oc1=-1
    x2=-1 y2=-1 c2=0 ox2=-1 oy2=-1 oc2=-1
    x3=-1 y3=-1 c3=0 ox3=-1 oy3=-1 oc3=-1
    c0=0 oxm=-1 oym=-1
    -w[-1] -1,-1,0,0,@{-2,b}.@{-2,x}
    -do  # Enter event loop.

      # Manage user interactions.
      -wait[0-3]
      oc0=$c0
      -repeat 4
        -if {$>" && "!@{!$>}" && "${x$>}>=0} -w$> 0 x$>=-1 y$>=-1 c$>=0 -endif
        -if @{!$>,o} c$>={(${c$>}+sign(@{!$>,o}))%s} -wait[$>] -1 -endif
        -if {@{!$>,SPACE}" || "@{!$>,ENTER}" || "@{!$>,ARROWRIGHT}" || "@{!$>,ARROWDOWN}} c$>={(${c$>}+1)%s} -wait[$>] -1 -endif
        -if {@{!$>,BACKSPACE}" || "@{!$>,ARROWLEFT}" || "@{!$>,ARROWUP}} c$>={(${c$>}-1)%s} -wait[$>] -1 -endif
      -done
      -if {$oc0!=$c0} c1=$c0 c2=$c0 c3=$c0 -endif
      xm=@{!,x} ym=@{!,y}
      -if {$xm>=0" && "@{!,b}&1} x1=$xm y1=$ym -endif
      -if {$xm>=0" && "@{!,b}&2} x2=$xm y2=$ym -endif
      -if {$xm>=0" && "@{!,b}&4} x3=$xm y3=$ym -endif

      # Generate main image view.
      -if {$xm>=0" && "($oxm!=$xm" || "$oym!=$ym)} -w[] -1,-1,-1,-1,@{-2,b}.@{-2,x}" - ("$xm,$ym")" -endif
      -if {$x1!=$ox1" || "$y1!=$oy1" || "$x2!=$ox2" || "$y2!=$oy2" || "$x3!=$ox3" || "$y3!=$oy3}
        [-1]
        -if {$x1>=0}
          xb={$x1-$dxb} yb={$y1-$dyb} xe={$x1+$dxf} ye={$y1+$dyf}
          -polygon[-1] 4,$xb,$yb,$xe,$yb,$xe,$ye,$xb,$ye,0.2,0,255,255
          -polygon[-1] 4,$xb,$yb,$xe,$yb,$xe,$ye,$xb,$ye,1,0xFFFFFFFF,0,255,255
        -endif
        -if {$x2>=0}
          xb={$x2-$dxb} yb={$y2-$dyb} xe={$x2+$dxf} ye={$y2+$dyf}
          -polygon[-1] 4,$xb,$yb,$xe,$yb,$xe,$ye,$xb,$ye,0.2,255,32,255
          -polygon[-1] 4,$xb,$yb,$xe,$yb,$xe,$ye,$xb,$ye,1,0xFFFFFFFF,255,32,255
        -endif
        -if {$x3>=0}
          xb={$x3-$dxb} yb={$y3-$dyb} xe={$x3+$dxf} ye={$y3+$dyf}
          -polygon[-1] 4,$xb,$yb,$xe,$yb,$xe,$ye,$xb,$ye,0.2,255,255,0
          -polygon[-1] 4,$xb,$yb,$xe,$yb,$xe,$ye,$xb,$ye,1,0xFFFFFFFF,255,255,0
        -endif
        -w[-1] @{-2,w},@{-2,h} -rm[-1] oxm=$xm oym=$ym
      -endif

      # Generate zoomed views.
      -if {$x1>=0" && "($ox1!=$x1" || "$oy1!=$y1" || "$oc1!=$c1)}
        --z[-2] {$x1-$dxb},{$y1-$dyb},0,$c1,{$x1+$dxf},{$y1+$dyf},0,$c1
        --z[-2] {$x1-$dxb},{$y1-$dyb},0,{$x1+$dxf},{$y1+$dyf},0
        -__display_array[-2,-1] $1,$2,0,255,255
        -w1[-1] @{-1,w},@{-1,h},0,0,@{-2,b}.@{-2,x}" - ("$x1,$y1,c=$c1")"
        -rm[-1] ox1=$x1 oy1=$y1 oc1=$c1
      -endif
      -if {$x2>=0" && "($ox2!=$x2" || "$oy2!=$y2" || "$oc2!=$c2)}
        --z[-2] {$x2-$dxb},{$y2-$dyb},0,$c2,{$x2+$dxf},{$y2+$dyf},0,$c2
        --z[-2] {$x2-$dxb},{$y2-$dyb},0,{$x2+$dxf},{$y2+$dyf},0
        -__display_array[-2,-1] $1,$2,255,32,255
        -w2[-1] @{-1,w},@{-1,h},0,0,@{-2,b}.@{-2,x}" - ("$x2,$y2,c=$c2")"
        -rm[-1] ox2=$x2 oy2=$y2 oc2=$c2
      -endif
      -if {$x3>=0" && "($ox3!=$x3" || "$oy3!=$y3" || "$oc3!=$c3)}
        --z[-2] {$x3-$dxb},{$y3-$dyb},0,$c3,{$x3+$dxf},{$y3+$dyf},0,$c3
        --z[-2] {$x3-$dxb},{$y3-$dyb},0,{$x3+$dxf},{$y3+$dyf},0
        -__display_array[-2,-1] $1,$2,255,255,0
        -w3[-1] @{-1,w},@{-1,h},0,0,@{-2,b}.@{-2,x}" - ("$x3,$y3,c=$c3")"
        -rm[-1] ox3=$x3 oy3=$y3 oc3=$c3
      -endif
    -while {@!" && "\
            !@{!,ESC}" && "!@{!,Q}" && "\
            !@{!1,ESC}" && "!@{!1,Q}" && "\
            !@{!2,ESC}" && "!@{!2,Q}" && "\
            !@{!3,ESC}" && "!@{!3,Q}}
    -rm[^0] -w 0 -w1 0 -w2 0 -w3 0
  -endl -done -v +

__display_array :
  -round[-2] 1 -c[-2] 0,999 -r[-1] 100%,100%,1,3,{if(s==1,1,0)}
  --luminance[-1] -r[-2] {$1*24},{$2*24} -grid[-2] {100/$1}%,{100/$2}%,0,0,1,0
  xb={24*int($1/2)} yb={24*int($2/2)} xe={$xb+24} ye={$yb+24}
  -polygon[-2] 4,$xb,$yb,$xe,$yb,$xe,$ye,$xb,$ye,1,0xFFFFFFFF,$3,$4,$5
  -repeat $2 yg=$>
    -repeat $1 xg=$>
      -text[-2] @{-3,($xg,$yg)},{5+$xg*24},{5+$yg*24},13,0.8,{if(@{-1,($xg,$yg)}>128,0,255)}
    -done
  -done
  -rm[-3,-1]

#@gmic dfft : eq. to '-display_fft'.
dfft :
  -_display_fft

#@gmic display_fft
#@gmic : Display fourier transform of selected images, with centered log-module and argument.
#@gmic : (eq. to '-dfft').
#@gmic : $ image.jpg --display_fft
display_fft :
  -_display_fft

_display_fft :
  -e[0--3] "Render fourier transform of image$? with centered log-module and argument."
  -v - -repeat @#
    -fftpolar[-1] -+[-2] 1 -log[-2] -n[-2,-1] 0,255 -a[-2,-1] x
  -mv[-1] 0 -done -s x,2 -v +

#@gmic dg : eq. to '-display_graph'.
dg :
  -_display_graph $*

#@gmic display_graph : _width>32,_height>32,_plot_type,_vertex_type,_xmin,_xmax,_ymin,_ymax
#@gmic : Render graph plot from selected image data.
#@gmic : Default values : 'width=640', 'height=480', 'plot_type=1', 'vertex_type=1' and 'xmin=xmax=ymin=ymax=0'.
#@gmic : $ 128,1,1,1,'cos(x/10+?)' --display_graph 400,300,3
display_graph :
  -_display_graph $*

_display_graph : -check "${1=640}>32 && ${2=480}>32" -skip ${3=1},${4=0},${5=0},${6=0},${7=0},${8=0}
  -e[0--3] "Render $1x$2 graph plot from data of image$?."
  -v - -repeat @#

    # Determine xmin,xmax/ymin,ymax.
    one={$3!=3} siz={w*h*d}
    -if {$5==$6} xmin=0 xmax={$siz-$one} -else xmin={min($5,$6)} xmax={max($5,$6)} -endif
    -if {$7==$8} ymin={im-(iM-im)/20} ymax={iM+(iM-im)/20} -else ymin={min($7,$8)} ymax={max($7,$8)} -endif

    # Create plot canvas.
    gw={$1-32} gh={$2-32} gg={($gw-$one)/($siz-$one)}
    $gw,$gh,1,3,255
    -if {$siz<32} -grid[-1] $gg,$gg,0,0,0.25,0xCCCCCCCC,0
    -else -grid[-1] 10%,10%,0,0,0.25,0xCCCCCCCC,0
    -endif

    # Define color palette for curves.
    -if {@{-2,s}==1} (0,0,255)
    -elif {@{-2,s}<=3} (255,0,0;0,255,0;0,0,255)
    -else
      (0,255) -r[-1] 256,1,1,1,3 -map[-1] 2 -z[-1] 2,100% -permute[-1] cxyz -r[-1] 3,{max(3,@{-3,s})},1,1,0,2
      -sh[-1] 0,2,0,0 -f[-1] 255,0,0,0,255,0,0,0,255 -rm[-1]
    -endif

    # Draw plot for each channel.
    -repeat @{-3,s} -sh[-3] $>,$> -graph[-3] [-1],$3,$4,$ymax,$ymin,1,@{-2,0-2} -rm[-1] -shift[-1] 0,-1 -done
    -rm[-3,-1]
    -line[-1] 0,0,100%,0,1,110 -line[-1] 100%,0,100%,100%,1,110
    -line[-1] 100%,100%,0,100%,1,255 -line[-1] 0,100%,0,0,1,255

    100%,100% -axes[-1] $xmin,{$xmin+($xmax-$xmin)*($siz-$one)/($siz-1)},$ymax,$ymin,13,1,1
    --dilate[-1] 3 --[-1] [-2] -*[-1] 200 -eq[-2] 0
    -*[-3,-2] -+[-2,-1] -c[-1] 0,255

    -frame[-1] 16,16,220
    1 -text[-1] "X-axis",0,0,13,1,-220,-220,-220 -j[-2] [-1],{(@{-2,w}-w)/2},{@{-2,h}-16},0,0,-1 -rm[-1]
    1 -text[-1] "Y-axis",0,0,13,1,-220,-220,-220 -rotate[-1] -90 -j[-2] [-1],2,{(@{-2,h}-h)/2},0,0,-1 -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic dh : eq. to '-display_histogram'.
dh :
  -_display_histogram $*

#@gmic display_histogram : _width>0,_height>0,_clusters>0,_max_value>0,_show_axes={ 0 | 1 }
#@gmic : Render a channel-by-channel histogram.
#@gmic : (eq. to '-dh').
#@gmic : Default values : 'width=512', 'height=300', 'clusters=256', 'max_value=255' and 'show_axes=1'.
#@gmic : $ image.jpg --display_histogram 512,300
display_histogram :
  -_display_histogram $*

_display_histogram : -check "${1=512}>0 && ${2=300}>0 && ${3=256}>0 && ${4=255}" -skip ${5=1}
  -e[0--3] "Render $1x$2 channel-by-channel histogram of image$?, with $3 clusters and maximum value $4."
  -v -
  -repeat @#
    -l[-1] -s c -histogram $3,0,$4
    --max M=@{-1,M} -rm[-1]
    -repeat @# $1,$2,1,1,-255 -graph[-1] [-2],3,0,$M,0,1,0,0 -rm[-2] -mv[-1] 0 -done
    -a c
    -if $5 -axes[-1] 0,$4,$M,0,13,1,-128 -endif
    -endl
    -+[-1] 255
  -mv[-1] 0 -done -v +

#@gmic dp : eq. to '-display_polar'.
dp :
  -_display_polar $*

#@gmic display_polar : _width>32,_height>32,_outline_type,_fill_R,_fill_G,_fill_B,_theta_start,_theta_end
#@gmic : Render polar curve from selected image data.
#@gmic : 'outline_type' can be { r<0=dots with radius -r | 0=no outline | r>0=lines+dots with radius r }.
#@gmic : 'fill_color' can be { -1=no fill | R,G,B=fill with specified color }.
#@gmic : Default values : 'width=500', 'height=width', 'outline_type=1', 'fill_R=fill_G=fill_B=200', 'theta_start=0' and 'theta_end=360'.
#@gmic : $ 300,1,1,1,'0.3+abs(cos(10*pi*x/w))+?(0.4)' -display_polar 512,512,4,200,255,200
#@gmic : $ 3000,1,1,1,'x^3/1e10' -display_polar 400,400,1,-1,,,0,{15*360}
display_polar :
  -_display_polar $*

_display_polar : -check "${1=500}>32 && ${2=$1}>32" -skip ${3=1},${4=200},${5=$4},${6=$5},${7=0},${8=360}
  -e[0--3] "Render $1x$2 polar graph plot from data of image$?, with outline $4 and fill color ($4,$5,$6)."
  -v - m3d=@* -m3d 2 -repeat @# -l[$>]

    # Compute (x,y) coordinates of the polar curve points.
    M={max(abs(iM),abs(im))}
    -* {0.48*min($1,$2)/$M}
    -y y ({$7*pi/180};{-$8*pi/180}) -r[-1] 1,[-2],1,1,3
    --sin[-1] -cos[-2] -*[-1] [-3] -*[-3,-2]
    -a[-2,-1] x N={h}
    -nm[-1] coords

    # Generate 3d object for curve outline.
    -if $3
      ({'CImg3d'}) -+[-1] 0.5 ($N,$N)
      --z[coords] 0,2
      1,$N,1,1,2 1,$N,1,1,'y' --+[-1] 1 -a[-3--1] x -=[-1] 0,2,100%
      3,$N,1,1,0 1,$N,1,1,1 -y[-6--1] y -a[-6--1] y
      -nm[-1] _plot_polar_outline
    -endif

    # Generate 3d object for filling.
    -if {"$4>=0 && $5>=0 && $6>=0"}
      ({'CImg3d'}) -+[-1] 0.5 ({$N+1},$N)
      --z[coords] 0,-1,2,100% -z[-1] 0,2
      1,$N,1,1,3 1,$N 1,$N,1,1,'1+y' --+[-1] 1 -a[-4--1] x -=[-1] 1,3,100%
      3,$N,1,1,$4,$5,$6 1,$N,1,1,1
      -y[-6--1] y -a[-6--1] y
      -nm[-1] _plot_polar_fill
    -endif
    -rm[coords]  # Remove original curve coordinates.

    # Render graph image.
    $1,$2,1,3,255
    L={0.1*max($1,$2)} -grid[-1] $L,$L,0,0,0.25,0xCCCCCCCC,0  # Draw background grid.
    -if {"$4>=0 && $5>=0 && $6>=0"}                           # Draw curve filling.
      -object3d[-1] [_plot_polar_fill],50%,50%,0,1,0
      -rm[_plot_polar_fill]
    -endif
    -if $3
      -if {$3>=0}                                             # Draw curve outline.
        -object3d[-1] [_plot_polar_outline],50%,50%,0,1,0
      -endif
      -if {$3!=0}                                             # Draw curve vertices.
        -if {abs($3)>1} -circles3d[_plot_polar_outline] {abs($3)} -endif
        -object3d[-1] [_plot_polar_outline],50%,50%,0,0.2,0
      -endif
      -rm[_plot_polar_outline]
    -endif

    # Draw axes and frame.
    nM={$M/0.96}
    100%,100% -axes[-1] {-$nM},$nM,$nM,{-$nM},13,1,1
    --dilate[-1] 3 --[-1] [-2] -*[-1] 200 -eq[-2] 0
    -*[-3,-2] -+[-2,-1] -c[-1] 0,255
    -frame[-1] 1,1,128 -frame[-1] 15,15,220

  -endl -done -m3d $m3d -v +

#@gmic drgba : eq. to '-display_rgba'.
drgba :
  -_display_rgba

#@gmic display_rgba
#@gmic : Render selected RGBA images over a checkerboard background.
#@gmic : (eq. to '-drgba').
#@gmic : $ image.jpg --norm -threshold[-1] 40% -blur[-1] 3 -normalize[-1] 0,255 -append c -display_rgba
display_rgba :
  -_display_rgba

_display_rgba :
  -e[0--3] "Render RGBA image$? over a checkerboard background."
  -v - -to_a -repeat @#
    -i[-2] (160,128;128,160) -nm[-2] @{-1,n} -r[-2] 16,16 -r[-2] [-1],[-1],1,{s-1},0,2 -compose_alpha[-2,-1]
  -mv[-1] 0 -done -v +

#@gmic dt : eq. to '-display_tensors'.
dt :
  -_display_tensors $*

#@gmic display_tensors : _size_factor>0,_ellipse_factor>=0,_colored_mode={ 0 | 1 }
#@gmic : Render selected mask field of 2x2 tensors with ellipses.
#@gmic : (eq. to '-dt').
#@gmic : Default values : 'size_factor=16', 'ellipse_factor=0.92', 'color_mode=1'.
#@gmic : $ image.jpg -diffusiontensors 0.7,0.6 -crop 60,10,90,30 --display_tensors ,
display_tensors :
  -_display_tensors $*

_display_tensors : -check "${1=16}>0 && ${2=0.92}>=0" -skip "${3=1}"
  -e[0--3] "Render field of 2x2 tensors from image$?, with size factor $1, ellipse factor $2 in "\
  @{"-if $3 -u colored -else -u masked -endif"}" mode."
  -v -
  -if {$3} -repeat @# -l[$>]
    --_display_tensors $1,$2,0
    -s[0] c --min[0,2] -*[1] -1 -+[1,-1] -a[0-2] c
    -r[0] [-1],[-1] -n[0] 0,255 -*
  -endl -done -else -repeat @# -l[$>]
    w={w} h={h}
    -* {($2*$1/2)^2/max(abs(im),abs(iM))}     # Normalize tensor values.
    -s c -i[-2] [-2] -a c -s yx -r 2,2,1,1,-1 # Decompose field into list of 2x2 matrices.
    (0.5,0;0,0.5) -+[0--2] [-1] -rm[-1]       # Add 0.5*Id to ensure tensor positivity.
    -invert -y c -r $1,$1                     # Optimized code for ellipses drawing.
    $1,$1,1,1,'x' --[-1] {w/2}
    $1,$1,1,1,'y' --[-1] {h/2}
    --sqr[-1] -*[-2] [-3] -sqr[-3] -i[-2] [-2] -a[-4--1] c
    -*[0--2] [-1] -rm[-1] -compose_channels + -le 1
    -append_tiles $w,$h                       # Recompose ellipses as a tensor field.
  -endl -done -endif
  -v +

#@gmic dw : eq. to '-display_warp'.
dw :
  -_display_warp $*

#@gmic display_warp : _cell_size>0
#@gmic : Render selected 2d warping fields.
#@gmic : (eq. to '-dw').
#@gmic : Default value : 'cell_size=15'.
#@gmic : $ image.jpg -luminance -blur 5 -gradient -append c -display_warp ,
display_warp :
  -_display_warp $*

_display_warp : -check "${1=15}>0"
  -e[0--3] "Render 2d warping field$?, with cell size $1."
  -v - -repeat @#
    -if {d!=1||s!=2}
      -error[0--3] "Invalid image ["{@#-$>-1}"] : Dimensions "{w}","{h}","{d}","{s}" does not represent a 2d field of 2d vectors."
    -endif
    100%,100%,1,1,'(x%$1)&&(y%$1)'
    -warp[-1] [-2],1,1,0 -rm[-2]
  -mv[-1] 0 -done -* 255 -v +

#@gmic function1d : 0<=smoothness<=1,x0>=0,y0,x1>=0,y1,...,xn>=0,yn
#@gmic : Generate continuous 1d function from specified list of keypoints (xk,yk)
#@gmic : in range [0,max(xk)] (xk are positive integers).
#@gmic : Default values : 'smoothness=1' and 'x0=y0=0'.
#@gmic : $ -function1d 1,0,0,10,30,40,20,70,30,80,0 --display_graph 400,300
function1d : -check "${1=1}>=0 && $1<=1" -skip ${2=0},${3=0}
  -e[^-1] "Generate continuous 1d function, with smoothness $1 and keypoints (${2--1})."
  -v -

  # Normalize input coordinates.
  -if {$#<5} {max(0,$2)+1},1,1,1,$3 -return -endif
  (${2--1}) -r[-1] 2,{w/2},1,1,-1 -sort[-1] +,y -s[-1] x,2 -round[-2] 1 -a[-2,-1] x

  # Estimate pointwise forward/backward slopes.
  --shift[-1] 0,1,0,0,1 --[-1] [-2] -*[-1] -1   # Backward derivatives.
  --shift[-2] 0,-1,0,0,1 --[-1] [-3]            # Forward derivatives.
  --*[-2] {$1/2} --*[-2] {1-$1/2} -+[-2,-1]     # Forward tangents.
  -*[-3] {1-$1/2} -*[-2] {$1/2} -+[-3,-2]       # Backward tangents.
  -s[-2,-1] x -+[-4,-2] 1e-10
  -/[-3] [-4] -/[-1] [-2] -rm[-4,-2]            # Forward and backward slopes.
  -a[-3--1] x                                   # Append slopes to coordinates.

  # Compute multi-spline curve.
  {@{-1,(0,{h-1})}+1}
  -repeat {@{-2,h}-1}
    xstart={if($>,@{-2,0},0)}
    -_function1d @{-2,0-1},@{-2,3},@{-2,4-6},$xstart,@{-2,4} -j[-2] [-1],$xstart -rm[-1]
  -shift[-2] 0,-1 -done
  -rm[-2]
  -v +

# Generate single spline function from specified coordinates (x0,y0,s0)-(x1,y1,s1), in range [t0..t1]
_function1d :
  ({$1^3},{$1^2},$1,1;\
   {3*$1^2},{2*$1},1,0;\
   {$4^3},{$4^2},$4,1;\
   {3*$4^2},{2*$4},1,0)
  ($2;$3;$5;$6) -solve[-1] [-2] -rm[-2] -transpose[-1]
  ($7,$8) -r[-1] {1+$8-$7},1,1,1,3 --^[-1] 3 --^[-2] 2 --f[-1] 1 -mv[-4] -1 -a[-4--1] y
  -**[-2,-1]

#@gmic gmicky
#@gmic : Load a new image of the G'MIC mascot 'Gmicky'.
#@gmic : $ -gmicky
gmicky :
  -e[^-1] "Load image of the G'MIC mascot 'Gmicky'."
  -v - -i http://gmic.sourceforge.net/img/gmicky_large.cimgz -v +

#@gmic gmicky_wilber
#@gmic : Load a new image of the G'MIC mascot 'Gmicky' together with GIMP mascot 'Wilber'.
#@gmic : $ -gmicky_wilber
gmicky_wilber :
  -e[^-1] "Load image of the G'MIC mascot 'Gmicky' together with GIMP mascot 'Wilber'."
  -v - -i http://gmic.sourceforge.net/img/gmicky_wilber_large.cimgz -v +

#@gmic img2text : _line_separator
#@gmic : Return text contained in a multi-line image.
#@gmic : Default value : 'line_separator= '.
img2text : -skip "${1= }"
  -v - --l -s y -s -,0 -y x -if {@#>1} -i[1--2] ({'"$1"'}) -endif -a x -u @{0,t} -rm -endl -v +

#@gmic on : eq. to '-outputn'.
on :
  -_outputn $*

#@gmic outputn : filename
#@gmic : Output selected images as automatically numbered filenames in repeat..done loops.
#@gmic : (eq. to '-on').
outputn :
  -_outputn $*

_outputn :
  -v - filename=@{"-filename \"$1\","@{>}} -v +
  -e[0--3] "Output image$? as file '"$filename"'."
  -v - -o $filename -v +

#@gmic op : eq. to '-outputp'.
op :
  -_outputp $*

#@gmic outputp : prefix
#@gmic : Output selected images as prefixed versions of their original filenames.
#@gmic : (eq. to '-op').
#@gmic : Default value : 'prefix=_'.
outputp :
  -_outputp $*

_outputp : -skip ${1="_"}
  -if {@#>1} -e[0--4] "Output image$? as their initial locations, prefixed by '$1'."
  -else -e[0--4] "Output image$? as its initial location, prefixed by '$1'."
  -endif
  -v - -repeat @# -o[$>] @{$>,f}$1@{$>,b}.@{$>,x} -done -v +

#@gmic ow : eq. to '-outputw'.
ow :
  -_outputw $*

#@gmic outputw
#@gmic : Output selected images by overwritting their original location.
#@gmic : (eq. to '-ow').
outputw :
  -_outputw $*

_outputw :
  -if {@#>1} -e[0--4] "Output image$? as their initial location."
  -else -e[0--4] "Output image$? as its initial location."
  -endif
  -v - -repeat @# -o[$>] @{$>,n} -done -v +

#@gmic rainbow_lut
#@gmic : Generate a 256-entries RGB colormap of rainbow colors.
#@gmic : $ image.jpg -rainbow_lut --luminance[-2] -map[-1] [-2]
rainbow_lut :
  -e[^-1] "Generate RGB colormap of rainbow colors."
  -v -
  (2,10,13,13,15,16,15,15,18,23,26,31,33,37,38,39,42,42,44,45,44,44,45,45,44,42,44,45,45,49,50,52,54,55,56,57,56,56,57,57,58,57,58,58,59,58,60,59,58,59,59,59,59,59,60,60,59,59,59,59,60,59,59,59,59,59,59,59,58,58,58,56,56,54,51,48,44,39,33,20,5,0,0,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,25,50,66,81,90,102,109,118,129,137,144,152,158,168,178,183,190,199,207,213,220,227,230,236,242,246,250,255,255,253,253,253,252,251,250,250,249,248,248,247,248,246,246,246,245,246,245,245,245,246,246,246,246,246,246,246,246,245,245,245,245,245,244,245,244,245,245,245,245,245,245,245,245,245,244,244,245,245,243,239,235,230,226,220,216,211,204,201,194,190,184,176,171,164,160,152,144,138,130,122,114,107,96,87,78,69,57,50,46,38,31,19,5^3,10,14,15,17,18,19,18,19,23,25,30,31,35,37,39,42,44,45,48,49,50,51,52,53,56,59,63,66,66,68,69,71,73,74,75,76,76,77,78,79,79,80,81,81,82,82,83,84,84,84,84,84,85,85,86,86,86,86,87,88,87,86,86,86,86,88,89,89,90,92,92,94,96,99,102,104,107,111,117,120,126,130,136,142,149,155,161,167,172,176,178,179,179,178,178,178,178,177,177,177,176,176,176,176,175,173,173,174,173,172,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,173,173,173,175,176,178,178,178,181,182,184,186,186,190,192,193,195,198,200,201,204,206,209,211,208,206,202,197,194,190,185,182,178,172,167,162,157,152,144,139,132,127,121,115,108,102,98,92,87,79,75,69,64,62,58,55,52,50,49,47,47,47,47,47,47,47,47,46,46,46,46,45,44,44,42,42,41,41,40,39,38,37,36,34,31,30,29,30,30,31,32,32,32,33,33,34,34,33,34,33,32,31,31,30,29,26,25,23,21,19,15,13,13,16,18,18,18,17,15,13,12,9,2^6,19,25,32,41,49,55,65,71,79,84,90,96,102,106,111,117,121,128,132,134,139,143,146,149,152,155,156,157,159,159,160,161,162,163,164,164,165,166,167,166,165,166,166,167,167,168,168,168,169,169,169,169,170,170,170,170,170,170,170,171,170,170,170,170,170,171,171,172,173,173,173,175,177,179,180,183,185,187,190,193,198,201,206,213,219,225,227,227,223,218,214,204,199,192,184,179,172,168,162,156,151,145,139,133,126,120,113,106,98,90,85,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,84,84,82,82,82,82,82,83,83,81,81,81,80,80,78,78,78,76,74,73,73,71,72,69,68,67,65,62,59,58,56,51,50,49,45,43,40,38,37,35,32,31,32,32,33,33,34,34,35,36,36,37,38,39,42,44,45,46,46,47,48,49,48,48,48,48,48,48,48,48,48,48,47,47,47,47,46,45,45,43,43,42,41,40,39,38,37,38,38,37,37,38,38,38,38,39,40,39,40,39,40,40,39,39,38,38,37,35,34,32,30,28,26,23,20,16,14,12,16,16,18,18,17,16,14,13,9,2)
  -v +

#@gmic roddy
#@gmic : Load a new image of the G'MIC Rodilius mascot 'Roddy'.
#@gmic : $ -roddy
roddy :
  -e[^-1] "Load image of the G'MIC Rodilius mascot 'Roddy'."
  -v - -i http://gmic.sourceforge.net/img/roddy_large.cimgz -v +

#@gmic rm_duplicates
#@gmic : Remove duplicates images in the selected images list.
#@gmic : $ (1,2,3,4,2,4,3,1,3,4,2,1) -split x -rm_duplicates -append x
rm_duplicates :
  -e[^-1] "Remove duplicates images in selected list of image$?."
  -v - -repeat @#
    base=$> off=0
    -repeat {@#-$>-1}
      comp={$base+1+$>-$off}
      -if {$comp>=@#} -break -endif
      ---[$base,$comp] -abs[-1] is_duplicate={!@{-1,+}} -rm[-1]
      -if $is_duplicate -rm[$comp] off={$off+1} -endif
    -done
  -done -v +

#@gmic sort_list : _ordering={ + | - },_x,_y,_z,_c
#@gmic : Sort list of selected images according to their value located at (x,y,z,c).
#@gmic : Default values : 'ordering=+', 'x=0', 'y=0', 'z=0' and 'c=0'.
#@gmic : (1;4;7;3;9;2;4;7;6;3;9;1;0;3;3;2) -split y -sort_list -append y
sort_list : -skip ${1=+},${2=0},${3=0},${4=0},${5=0}
  -e[^-1] "Sort list of image$? in "@{"-if {$1'=='+} -u ascending -else -u descending -endif"}" order, "\
          "according to their value located at ($2,$3,$4,$5)."
  -v - -if @#
    i=@# --z $2,$3,$4,$5,$2,$3,$4,$5 -a[$i--1] y --f[-1] 'y' -a[-2,-1] x -sort[-1] $1,y -z[-1] 1,1
    -repeat {h} name$>=@{$>,n} -nm[$>] sortlist$> -done
    -repeat {h} -mv[sortlist{i(0,$>)}] -1 -done
    -repeat {h} -nm[$>] ${name{i(0,$>)}} -done
  -rm[-1] -endif -v +

#@gmic testimage2d : _width>0,_height>0,_spectrum>0
#@gmic : Generate a synthetic image.
#@gmic : Default values : 'width=512', 'height=width' and 'spectrum=3'.
#@gmic : $ -testimage2d 512
testimage2d : -check "${1=512}>0 && ${2=$1}>0 && ${3=3}>0"
  -e[^-1] "Generate 2d test image with size $1x$2x$3."
  -v -
  Dmax2={0.15*min($1,$2)^2}
  $1,$2,1,$3,'X=x-w/2;Y=y-h/2;a=atan2(Y,X);if(X^2+Y^2<=$Dmax2,255*abs(cos(c+200*(x/w-0.5)*(y/h-0.5))),850*(a%(0.1*(c+1))))'
  -polygon[-1] 4,20%,20%,60%,20%,70%,70%,35%,45%,0.9,0,255,0
  -torus3d {$1/7},{$1/20} -r3d[-1] 0,1,1,80 -db3d 0 -m3d 5 -col3d[-1] 128,200,255
  -object3d[-2] [-1],30%,70% -rm[-1]
  -v +

#@gmic text2img : text,_line_separator
#@gmic : Generate a new 2d image where values are ASCII characters of specified input text.
#@gmic : Default value : 'line_separator= '.
#@gmic : $ -text2img "There are 4 words"
text2img : -skip "${2= }"
  -e[^-1] "Generate image from text \"$1\", with line separator '$2'."
  -v - ({'"$1"'}) -l[-1] -s -,{'"$2"'} -y x -a y -endl -v +

#@gmic up : eq. to '-update'.
up :
  -_update

#@gmic update
#@gmic : Update commands from the latest definition file on the G'MIC server.
#@gmic : This requires an active Internet connection and an access to the external
#@gmic : tools 'curl' or 'wget'.
#@gmic : (eq. to '-up').
update :
  -_update

_update :
  -e[0--3] "Update commands from the latest definition file on the G'MIC server."
  -v - -m http://gmic.sourceforge.net/gmic_def.@. -v +

#---------------------------------
#
#@gmic :: Values manipulation
#
#---------------------------------

#@gmic apply_curve : 0<=smoothness<=1,x0,y0,x1,y1,x2,y2,...,xN,yN
#@gmic : Apply curve transformation to image values.
#@gmic : Default values : 'smoothness=1', 'x0=0', 'y0=100'.
#@gmic : $ image.jpg --apply_curve 1,0,0,128,255,255,0
apply_curve : -check "${1=1}>=0 && $1<=1" -skip ${2=0},${3=100}
  -e[^-1] "Apply intensity curve with smoothness $1 and keypoints (${2--1}) on image$?."
  -v - -function1d ${^0} -map[0--2] [-1] -rm[-1] -v +

#@gmic apply_gamma : gamma>=0
#@gmic : Apply gamma correction to selected images.
#@gmic : $ image.jpg --apply_gamma 2
apply_gamma : -check $1>=0
  -e[^-1] "Apply Gamma-correction to image$?, with gamma $1."
  -if {$1==1} -return -endif
  -v - -repeat @#
    (@{-1,m},@{-1,M}) -n[-2] 0,1 -^[-2] {1/$1} -n[-2] @-1 -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic balance_gamma : _ref_color1,...
#@gmic : Apply color balance transformation on selected image, with respect to specified reference color.
#@gmic : Default values : 'ref_color1=128'.
#@gmic : $ image.jpg --balance_gamma 128,64,64
balance_gamma : -skip ${1=128}
  -e[^-1] "Apply color balance transformation on image$?, with gamma curve and reference color ("${^0}")."
  -v - -repeat @# -l[$>]
    (${^0}) -r[-1] @{-2,s},1,1,1,0,1 -s[-2] c -/[-1] 255
    -repeat {@#-1} -/[$>] 255 -^[$>] {log(@{-1,$>})/log(@{$>,a})} -*[$>] 255 -done
    -a[0--2] c -rm[-1] -n 0,255
  -endl -done -v +

#@gmic complex2polar
#@gmic : Compute complex to polar transforms of selected images.
#@gmic : $ image.jpg --fft -complex2polar[-2,-1] -log[-2] -shift[-2] 50%,50%,0,0,2 -remove[-1]
complex2polar :
  -e[^-1] "Compute complex to polar transforms of image$?."
  -v - -repeat {int(@#/2)}
    -r[-1] [-2],3 --atan2[-1] [-2] -sqr[-3,-2] -+[-3,-2] -sqrt[-2]
  -mv[-2,-1] 0 -done -v +

#@gmic cumul
#@gmic : Compute the cumulative function of specified image data.
#@gmic : $ image.jpg --histogram 256 --cumul[-1] -display_graph[-2,-1] 400,300,3
cumul :
  -e[^-1] "Compute cumulative of function$?."
  -v - -repeat @#
    dim={w},{h},{d},{s} -y[-1] x
    -repeat {round(log(w)/log(2),1,1)} --shift[-1] {2^$>} -+[-2,-1] -done
    -r[-1] $dim,-1
  -mv[-1] 0 -done -v +

#@gmic discard : value,_remove_if_not_found = { 0 | 1 }.
#@gmic : Remove specified value in selected images and return results as single-column vector.
#@gmic : Default value : 'remove_if_not_found'=0.
#@gmic : $ (1;2;3;4;3;2;1) --discard 2
discard : -skip ${2=0}
  -e[^-1] "Remove value $1 in image$?."
  -v - -repeat @# -l[$>]
    -s -,$1 -a y
    -if {!@#" && "!$2} 1,1,1,1,$1 -endif
  -endl -done -v +

#@gmic eigen2tensor
#@gmic : Recompose selected pairs of eigenvalues/eigenvectors as 2x2 or 3x3 tensor fields.
eigen2tensor :
  -e[^-1] "Recompose pairs in eigen field$? as 2x2 or 3x3 tensor fields."
  -v - -repeat {@#/2}
    -if {s==2} # 2d tensors.
      -s[-1] c
      --sqr[-1] -*[-2] [-3] -sqr[-3] # u^2 uv v^2
      -sh[-1] --*[-3] -1 -sh[-5]     # v^2 -uv u^2
      -a[-3--1] c -a[-4--2] c
      -sh[-3] 0,0 -*[-3,-1]          # l1*(u^2;uv;v^2)
      -sh[-3] 1,1 -*[-2,-1]          # l2*(v^2;-uv;u^2)
      -rm[-3] -+[-2,-1]
    -elif {s==6} # 3d tensors.
      -s[-1] c
      -l[-6--4] --sqr[-2] --*[-2,-3] --sqr[-3] -*[-5] [-6] -*[-4] [-6] -sqr[-6] -a c -endl
      -l[-3--1] --sqr[-2] --*[-2,-3] --sqr[-3] -*[-5] [-6] -*[-4] [-6] -sqr[-6] -a c -endl
      -s[-3] c
      --[-5] [-3] --[-4] [-3] -*[-2] [-5] -*[-1] [-4]
      (1^0^0^1^0^1) -r[-1] [-3] -*[-1] [-4] -rm[-6--4] -+[-3--1]
    -else -error[0--3] "Invalid image ["{@#-$>-1}"] : Dimensions "{w}","{h}","{d}","{s}" does not represent a field of 2d or 3d eigenvectors."
    -endif

  -mv[-1] 0 -done -v +

#@gmic float2int8
#@gmic : Convert selected float-valued images to 8bits integer representations.
float2int8 :
  -e[^-1] "Convert float-valued image$? to 8bits integer representations."
  -v - -repeat @# -l[$>]
    -s c
    -repeat @#
      m=@{-1,m} M=@{-1,M} -quantize[-1] 16777216,0
      -->>[-1] 8 -and[-1] 255 --and[-2] 255 ->>[-3] 16
      ({'$m,$M'})
      -a[-4--1] y
    -mv[-1] 0 -done
    -a c
  -endl -done -v +

#@gmic int82float
#@gmic : Convert selected 8bits integer representations to float-valued images.
int82float :
  -e[^-1] "Convert 8bits integer representation$? to float-valued image$?."
  -v - -repeat @#
    -l[$>]
    -s c
    -repeat @#
      -sh[-1] {h-1},{h-1},0,0 m=@{-1,t} -rm[-1]
      -lines[-1] 0,{h-2} -s[-1] y,3 -*[-3] 65536 -*[-2] 256 -or[-3--1]
      -n[-1] $m
    -mv[-1] 0 -done
    -a c
  -endl -done -v +

#@gmic mix_channels : (a00,...,aMN)
#@gmic : Apply specified matrix to channels of selected images.
#@gmic : $ image.jpg --mix_channels (0,1,0;1,0,0;0,0,1)
mix_channels :
  -e[^-1] "Apply matrix $1 to channels of image$?."
  -v - -repeat @#
    whd={w},{h},{d}
    -r[-1] {w*h*d},{s},1,1,-1
    -i[-2] ${^0} -**[-2,-1]
    -r[-1] $whd,{h},-1
  -mv[-1] 0 -done -v +

#@gmic negative
#@gmic : Compute negative of selected images.
#@gmic : $ image.jpg --negative
negative :
  -e[^-1] "Compute negative of image$?."
  -v - -repeat @# --[-1] {iM} -mv[-1] 0 -done -* -1 -v +

#@gmic normalize_sum
#@gmic : Normalize selected images with a unitary sum.
#@gmic : $ image.jpg --histogram[-1] 256 -normalize_sum[-1] -display_graph[-1] 400,300
normalize_sum :
  -e[^-1] "Normalize image$? with a unitary sum."
  -v - -repeat @# sum=@{$>,+} -if {$sum!=0} -/[$>] $sum -endif -done -v +

#@gmic otsu : _nb_levels>0
#@gmic : Hard-threshold image using Otsu's method.
#@gmic : Default value : 'nb_levels=256'.
#@gmic : $ image.jpg -luminance --otsu ,
otsu : -check "isint(${1=256}) && $1>0"
  -e[^-1] "Hard-threshold image$? using Otsu's method, with $1 histogram levels."
  -v - -n 0,{$1-1} -repeat @#
    --histogram[-1] $1 total=@{-1,+}
    --*[-1] 'x' sum=@{-1,+} -rm[-1]
    sumB=0 wB=0 wF=0 varMax=0 threshold=0
    -repeat $1
      wB={$wB+@{-1,$>}}
      -if {$wB==0} -continue -endif
      wF={$total-$wB}
      -if {$wF==0} -break -endif
      sumB={$sumB+$>*@{-1,$>}}
      mB={$sumB/$wB}
      mF={($sum-$sumB)/$wF}
      varBetween={$wB*$wF*($mB-$mF)^2}
      -if {$varBetween>$varMax} varMax=$varBetween threshold=$> -endif
    -done
    -rm[-1] -t[-1] $threshold
    -v + -e[] "  > Threshold for image ["$>"] ("@{-1,b}") : "$threshold -v -
  -mv[-1] 0 -done -v +

#@gmic polar2complex
#@gmic : Compute polar to complex transforms of selected images.
polar2complex :
  -e[^-1] "Compute polar to complex transforms of image$?."
  -v - -repeat {int(@#/2)}
    -r[-1] [-2],3 --sin[-1] -cos[-2] -*[-1] [-3] -*[-3,-2]
  -mv[-2,-1] 0 -done -v +

#@gmic replace : value_src,value_dest
#@gmic : Replace pixel values in selected images.
#@gmic : $ (1;2;3;4) --replace 2,3
replace :
  -e[^-1] "Replace pixel values $1 with $2 in image$?."
  -v - -repeat @#
    --==[-1] $1 -*[-1] {$2-$1} -+[-2,-1]
  -mv[-1] 0 -done -v +

#@gmic replace_inf : _expression
#@gmic : Replace all infinite values in selected images by specified expression.
#@gmic : $ (0;1;2) -log --replace_inf 2
replace_inf :
  -e[^-1] "Replace all infinite values in image$? by expression '$1'."
  -v - -f "if(i==i+1,$1,i)" -v +

#@gmic replace_nan : _expression
#@gmic : Replace all NaN values in selected images by specified expression.
#@gmic : $ (-1;0;2) -sqrt --replace_nan 2
replace_nan :
  -e[^-1] "Replace all NaN values in images$? by expression '$1'."
  -v - -f "if(i>=0 || i<=0,i,$1)" -v +

#@gmic replace_seq : "search_seq","replace_seq"
#@gmic : Search and replace a sequence of values in selected images.
#@gmic : $ (1;2;3;4;5) --replace_seq "2,3,4","7,8"
replace_seq :
  -e[^-1] "Replace value sequence '$1' by value sequence '$2' in image$?."
  -v - ($1) ($2) -repeat {@#-2} -l[$>,-2,-1]
    -s[0] +,$1 -s y,-@{-2,w}
    -repeat {@#-2} -if {@{$>,t}'=='@{-2,t}} -lines[$>] 0,{w-1} -f[$>] [-1] -endif -done
    -a[0--3] y
  -endl -done -rm[-2,-1] -v +

#@gmic roundify : gamma>=0
#@gmic : Apply roundify transformation on float-valued data, with specified gamma.
#@gmic : Default value : 'gamma=0'.
#@gmic : $ 1000 -fill '4*x/w' -repeat 5 --roundify[0] {$>*0.2} -done -append c -display_graph 400,300
roundify : -check $1>=0
  -e[^-1] "Roundify image$?, with gamma $1."
  -if {$1==1} -return -endif
  -v - -repeat @#
    --round[-1] 1 --[-2] [-1]
    --*[-2] 2 -abs[-1] -^[-1] $1 -sign[-3] -*[-3,-1] -*[-2] 0.5 -+[-2,-1]
  -mv[-1] 0 -done -v +

#@gmic t2 : eq. to '-threshold2'.
t2 :
  -_threshold2 $*

#@gmic threshold2 : min[%],max[%]
#@gmic : Threshold selected images between the two given values.
#@gmic : (eq. to '-t2').
#@gmic : $ image.jpg --threshold2 25%,75%
threshold2 :
  -_threshold2 $*

_threshold2 :
  -e[0--3] "Hard-threshold image$? between values $1 and $2."
  -v - -repeat @#
    --ge[-1] $1 -le[-2] $2 -and[-2,-1]
  -mv[-1] 0 -done -v +

#@gmic vector2tensor
#@gmic : Convert selected vector fields to corresponding diffusion tensor fields.
vector2tensor :
  -e[^-1] "Convert vector field$? to diffusion tensor field$?."
  -v - -repeat @# -l[-1]
    -s c
    -if {@#==2} --sqr[-1] -*[-2] [-3] -sqr[-3]
    -elif {@#==3} --sqr[-2] --*[-3] [-2] --sqr[-3] -*[-5,-4] [-6] -sqr[-6]
    -else -error[0--4] "Invalid image ["{@#-$>-1}"] : Dimensions "{w}","{h}","{d}","{s}" does not represent a field of 2d or 3d vectors."
    -endif
    -a c
  -endl -mv[-1] 0 -done -v +

#---------------------------------
#
#@gmic :: Colors manipulation
#
#---------------------------------

#@gmic apply_channels : "command",_channels={All,RGBA,RGB,Y,CbCr,Cb,Cr,L,ab,a,b,H,S,V,K,A,ch,c,h,R,G,B,A},_normalize={ 0=cut | 1=normalize }
#@gmic : Apply specified command on chosen normalized channels of each selected images.
#@gmic : Default value : 'normalize=0'.
#@gmic : $ image.jpg --apply_channels "-equalize 256 -blur 2",5
apply_channels : -skip ${3=0}

  # Process all channels.
  -if {$2==0}
    -e[^-1] "Apply command '$1' on image$?." -v -
    -repeat @# -l[-1]
      -_apply_channels "$1"
      -if $3 -n 0,255 -else -c 0,255 -endif
    -endl -mv[-1] 0 -done

  # Process RGBA channels.
  -elif {$2==1}
    -e[^-1] "Apply command '$1' on RGBA channels of image$?." -v -
    -to_rgba -repeat @# -l[-1]
      -_apply_channels "$1"
      -if $3 -n 0,255 -else -c 0,255 -endif
    -endl -mv[-1] 0 -done

  # Process RGB channels.
  -elif {$2==2}
    -e[^-1] "Apply command '$1' on RGB channels of image$?." -v -
    -repeat @# -l[-1]
      -split_opacity -to_rgb[0]
      -_apply_channels[0] "$1"
      -if $3 -n[0] 0,255 -else -c[0] 0,255 -endif
      -to_rgb[0]
      -a c
    -endl -mv[-1] 0 -done

  # Process Y channel.
  -elif {$2==3}
    -e[^-1] "Apply command '$1' on luminance of image$?." -v -
    -repeat @# -l[-1]
      -split_opacity -to_rgb[0] -rgb2ycbcr[0] -s[0] c
      -_apply_channels[0] "$1" -channels[0] 0
      -if $3 -n[0] 0,255 -else -c[0] 0,255 -endif
      -a[0-2] c -ycbcr2rgb[0] -a c
    -endl -mv[-1] 0 -done

  # Process CbCr channels.
  -elif {$2==4}
    -e[^-1] "Apply command '$1' on blue and red chrominances of image$?." -v -
    -repeat @# -l[-1]
      -split_opacity -to_rgb[0] -rgb2ycbcr[0] -s[0] c -a[1,2] c
      -_apply_channels[1] "$1" -channels[1] 0,1
      -if $3 -n[1] 0,255 -else -c[1] 0,255 -endif
      -a[0-1] c -ycbcr2rgb[0] -a c
    -endl -mv[-1] 0 -done

  # Process Cb channel.
  -elif {$2==5}
    -e[^-1] "Apply command '$1' on blue chrominance of image$?." -v -
    -repeat @# -l[-1]
      -split_opacity -to_rgb[0] -rgb2ycbcr[0] -s[0] c
      -_apply_channels[1] "$1" -channels[1] 0
      -if $3 -n[1] 0,255 -else -c[1] 0,255 -endif
      -a[0-2] c -ycbcr2rgb[0] -a c
    -endl -mv[-1] 0 -done

  # Process Cr channel.
  -elif {$2==6}
    -e[^-1] "Apply command '$1' on red chrominance of image$?." -v -
    -repeat @# -l[-1]
      -split_opacity -to_rgb[0] -rgb2ycbcr[0] -s[0] c
      -_apply_channels[2] "$1" -channels[2] 0
      -if $3 -n[2] 0,255 -else -c[2] 0,255 -endif
      -a[0-2] c -ycbcr2rgb[0] -a c
    -endl -mv[-1] 0 -done

  # Process L channel.
  -elif {$2==7}
    -e[^-1] "Apply command '$1' on lightness of image$?." -v -
    -repeat @# -l[-1]
      -split_opacity -to_rgb[0] -rgb2lab[0] -s[0] c
      -*[0] 2.55 -_apply_channels[0] "$1" -channels[0] 0 -/[0] 2.55
      -if $3 -n[0] 0,100 -else -c[0] 0,100 -endif
      -a[0-2] c -lab2rgb[0] -a c
    -endl -mv[-1] 0 -done

  # Process a-b channels.
  -elif {$2==8}
    -e[^-1] "Apply command '$1' on a-b channels of image$?." -v -
    -repeat @# -l[-1]
      -split_opacity -to_rgb[0] -rgb2lab[0] -s[0] c
      -+[1] 86 -*[1] 1.38587 -+[2] 108 -*[2] 1.25616
      -a[1,2] c -_apply_channels[1] "$1" -channels[1] 0,1 -s[1] c
      -/[1] 1.38587 --[1] 86 -/[2] 1.25616 --[2] 108
      -if $3 -n[1] -86,98 -n[2] -108,95 -endif
      -a[0-2] c -lab2rgb[0] -a c
    -endl -mv[-1] 0 -done

  # Process a-channel.
  -elif {$2==9}
    -e[^-1] "Apply command '$1' on a-channel of image$?." -v -
    -repeat @# -l[-1]
      -split_opacity -to_rgb[0] -rgb2lab[0] -s[0] c
      -+[1] 86 -*[1] 1.38587 -_apply_channels[1] "$1" -channels[1] 0 -/[1] 1.38587 --[1] 86
      -if $3 -n[1] -86,98 -endif
      -a[0-2] c -lab2rgb[0] -a c
    -endl -mv[-1] 0 -done

  # Process b-channel.
  -elif {$2==10}
    -e[^-1] "Apply command '$1' on b-channel of image$?." -v -
    -repeat @# -l[-1]
      -split_opacity -to_rgb[0] -rgb2lab[0] -s[0] c
      -+[2] 108 -*[2] 1.25616 -_apply_channels[2] "$1" -channels[2] 0 -/[2] 1.25616 --[2] 108
      -if $3 -n[1] -108,95 -endif
      -a[0-2] c -lab2rgb[0] -a c
    -endl -mv[-1] 0 -done

  # Process H channel.
  -elif {$2==11}
    -e[^-1] "Apply command '$1' on hue of image$?." -v -
    -repeat @# -l[-1]
      -split_opacity -to_rgb[0] -rgb2hsv[0] -s[0] c
      -*[0] 0.708333 -_apply_channels[0] "$1" -channels[0] 0 -/[0] 0.708333
      -if $3 -n[0] 0,360 -else -%[0] 360 -endif
      -a[0-2] c -hsv2rgb[0] -a c
    -endl -mv[-1] 0 -done

  # Process S channel.
  -elif {$2==12}
    -e[^-1] "Apply command '$1' on saturation of image$?." -v -
    -repeat @# -l[-1]
      -split_opacity -to_rgb[0] -rgb2hsv[0] -s[0] c
      -*[1] 255 -_apply_channels[1] "$1" -channels[1] 0 -/[1] 255
      -if $3 -n[1] 0,1 -else -c[1] 0,1 -endif
      -a[0-2] c -hsv2rgb[0] -a c
    -endl -mv[-1] 0 -done

  # Process V channel.
  -elif {$2==13}
    -e[^-1] "Apply command '$1' on value of image$?." -v -
    -repeat @# -l[-1]
      -split_opacity -to_rgb[0] -rgb2hsv[0] -s[0] c
      -*[2] 255 -_apply_channels[2] "$1" -channels[2] 0 -/[2] 255
      -if $3 -n[2] 0,1 -else -c[2] 0,1 -endif
      -a[0-2] c -hsv2rgb[0] -a c
    -endl -mv[-1] 0 -done

  # Process K channel.
  -elif {$2==14}
    -e[^-1] "Apply command '$1' on key channel of image$?." -v -
    -repeat @# -l[-1]
      -split_opacity -to_rgb[0] -rgb2cmyk[0] -s[0] c
      -_apply_channels[3] "$1" -channels[3] 0
      -if $3 -n[3] 0,255 -else -c[3] 0,255 -endif
      -a[0-3] c -cmyk2rgb[0] -a c
    -endl -mv[-1] 0 -done

  # Process Alpha channel.
  -elif {$2==15}
    -e[^-1] "Apply command(s) '$1' on alpha channel of image$?." -v -
    -repeat @# -l[-1]
      -to_rgba -split_opacity
      -_apply_channels[1] "$1" -channels[1] 0
      -if $3 -n[1] 0,255 -else -c[1] 0,255 -endif
      -a c
    -endl -mv[-1] 0 -done

  # Process c-h channels.
  -elif {$2==16}
    -e[^-1] "Apply command '$1' on c-h channels of image$?." -v -
    -repeat @# -l[-1]
      -split_opacity -to_rgb[0] -rgb2lch[0] -s[0] c
      -*[1] 2.55 -+[2] {pi} -*[2] {255/(2*pi)}
      -a[1,2] c -_apply_channels[1] "$1" -channels[1] 0,1 -s[1] c
      -/[1] 2.55 -/[2] {255/(2*pi)} --[2] {pi}
      -if $3 -n[1] 0,100 -n[2] -{pi},{pi} -endif
      -a[0-2] c -lch2rgb[0] -a c
    -endl -mv[-1] 0 -done

  # Process c-channel.
  -elif {$2==17}
    -e[^-1] "Apply command '$1' on c-channel of image$?." -v -
    -repeat @# -l[-1]
      -split_opacity -to_rgb[0] -rgb2lch[0] -s[0] c
      -*[1] 2.55 -_apply_channels[1] "$1" -channels[1] 0 -/[1] 2.55
      -if $3 -n[1] 0,100 -else -c[1] 0,100 -endif
      -a[0-2] c -lch2rgb[0] -a c
    -endl -mv[-1] 0 -done

  # Process h-channel.
  -elif {$2==18}
    -e[^-1] "Apply command '$1' on h-channel of image$?." -v -
    -repeat @# -l[-1]
      -split_opacity -to_rgb[0] -rgb2lch[0] -s[0] c
      -+[2] {pi} -*[2] {255/(2*pi)} -_apply_channels[2] "$1" -channels[2] 0 -/[2] {255/(2*pi)} --[2] {pi}
      -if $3 -n[2] -{pi},{pi} -endif
      -a[0-2] c -lch2rgb[0] -a c
    -endl -mv[-1] 0 -done

  # Process R channels.
  -elif {$2==19}
    -e[^-1] "Apply command '$1' on red channel of image$?." -v -
    -repeat @# -l[-1]
      -split_opacity -to_rgb[0] -s[0] c
      -_apply_channels[0] "$1"
      -if $3 -n[0] 0,255 -else -c[0] 0,255 -endif
      -to_gray[0]
      -a c
    -endl -mv[-1] 0 -done

  # Process G channels.
  -elif {$2==20}
    -e[^-1] "Apply command '$1' on green channel of image$?." -v -
    -repeat @# -l[-1]
      -split_opacity -to_rgb[0] -s[0] c
      -_apply_channels[1] "$1"
      -if $3 -n[1] 0,255 -else -c[1] 0,255 -endif
      -to_gray[1]
      -a c
    -endl -mv[-1] 0 -done

  # Process B channels.
  -elif {$2==21}
    -e[^-1] "Apply command '$1' on blue channel of image$?." -v -
    -repeat @# -l[-1]
      -split_opacity -to_rgb[0] -s[0] c
      -_apply_channels[2] "$1"
      -if $3 -n[2] 0,255 -else -c[2] 0,255 -endif
      -to_gray[2]
      -a c
    -endl -mv[-1] 0 -done

  # Process A channels.
  -elif {$2==22}
    -e[^-1] "Apply command '$1' on alpha channel of image$?." -v -
    -repeat @# -l[-1]
      -to_rgba -s c
      -_apply_channels[3] "$1"
      -if $3 -n[3] 0,255 -else -c[3] 0,255 -endif
      -to_gray[3]
      -a c
    -endl -mv[-1] 0 -done

  -endif
  -v +

_apply_channels :
  $* -k[0]

#@gmic autoindex : nb_colors>0,_dithering>=0,_method={ 0=median-cut | 1=k-means }
#@gmic : Index selected vector-valued images by adapted colormaps.
#@gmic : Default values : 'dithering=0' and 'method=0'.
#@gmic : $ image.jpg --autoindex 8
autoindex : -check "isint($1) && $1>0 && ${2=0}>=0" -skip ${3=0}
  -e[^-1] "Index colors in images$? by adapted colormap with $1 entries, dithering level $2 and "\
          @{"-if $3 -u k-means -else -u median-cut -endif"}" method."
  -v - -repeat @#
    -if {w>h} -if {w>256} --r2dx[-1] 256 -else [-1] -endif
    -else -if {h>256} --r2dy[-1] 256 -else [-1] -endif
    -endif
    -colormap[-1] $1,$3
    -index[-2] [-1],$2,1 -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic bayer2rgb : _GM_smoothness,_RB_smoothness1,_RB_smoothness2
#@gmic : Transform selected RGB-Bayer sampled images to color images.
#@gmic : Default values : 'GM_smoothness=RB_smoothness=1' and 'RB_smoothness2=0.5'.
#@gmic : $ image.jpg -rgb2bayer 0 --bayer2rgb 1,1,0.5
bayer2rgb : -skip ${1=1},${2=1},${3=0.5}
  -e[^-1] "Transform RGB-Bayer image$? to color images, with smoothness ($1,$2,$3)."
  -v - -channels 0 -repeat @#

    # Expand image size to avoid problems with borders.
    -expand_x[-1] {"2 + 4*$1"},0 -expand_y[-1] {"2 + 4*$1"},0

    # Compute green-magenta chromaticity.
    (-1,1;1,-1) -r[-1] [-2],[-2],1,1,0,2
    --*[-2] [-1]

    (0.25,0.5,0.25) -convolve[-2] [-1] -transpose[-1] -convolve[-2] [-1] -rm[-1]
    -b[-1] $1

    -*[-2] [-1]
    --[-3,-2]

    # Compute red-blue chromaticity.
    (1,-1) -r[-1] [-2],[-2],1,1,0,2  # Horizontal estimate
    -*[-1] [-3]
    (0.25,0.5,0.25) -convolve[-2] [-1] -transpose[-1] -convolve[-2] [-1] -rm[-1]
    -blur_y[-1] $2 -blur_x[-1] $3

    (1;-1) -r[-1] [-2],[-2],1,1,0,2  # Vertical estimate
    -*[-1] [-4]
    (0.25,0.5,0.25) -convolve[-2] [-1] -transpose[-1] -convolve[-2] [-1] -rm[-1]
    -blur_x[-1] $2 -blur_y[-1] $3

    -+[-2,-1] -/[-1] 2

    # Luminance reconstruction.
    (2,0;0,-2) -r[-1] [-2],[-2],1,1,0,2
    -*[-1] [-2]
    --[-4,-1]

    # RGB reconstruction.
    -a[-3--1] c
    -mix_rgb[-1] 1,-1,2,1,1,0,1,-1,-2

    # Shrink to original image size.
    -shrink_x[-1] {"2 + 4*$1"},0 -shrink_y[-1] {"2 + 4*$1"},0
    -c[-1] 0,255

  -mv[-1] 0 -done -v +

#@gmic colormap : nb_colors>0,_method={ 0=median-cut | 1=k-means }
#@gmic : Estimate best-fitting colormap with 'nb_colors' entries, to index selected images.
#@gmic : Default value : 'method=0'.
#@gmic : $ image.jpg --colormap[0] 4 --colormap[0] 8 --colormap[0] 16
colormap : -check "isint($1) && $1>0" -skip ${2=0}
  -e[^-1] "Estimate colormap with $1 entries for image$?, by "\
          @{"-if $2 -u k-means -else -u median-cut -endif"}" method."
  -v - -repeat @# -l[$>]
    -r {w*h},1,1,100%,-1
    -if {!$2} -_colormap $1                                 # Just run the median-cut algorithm.
    -else
      m={im} M={iM} -n[-1] 0,255                            # Keep track of the initial statistics.
      --_colormap $1 --index[-2] [-1] -*[-1] 256 -+[-3,-1]  # Initialize k-means labels and add them on the image.

      # Start k-means iterations.
      -do
        -repeat {s}                                             # Estimate new colormap.
          -sh[0] $>,$> --histogram[-1] {$1*256},0,{$1*256-1} -rm[-2]
          -i[-2] 256,1,1,1,'x' -r[-2] {w},1,1,1,0,2 -*[-2] [-1] -r[-2,-1] $1,1,1,1,2 -max[-1] 0.01 -/[-2,-1]
        -done -a[2--1] c
        --[-2] [-1] -abs[-2] diff={@{-2,+}/w} -rm[-2]           # Compute colormap difference.
        -and[-2] 255 --index[-2] [-1],0,0 -*[-1] 256 -+[-3,-1]  # Compute new k-means labels.
      -while {$diff>0.5}
      -rm[-2] -*[-1] {($M-$m)/255} -+[-1] $m                    # Convert colormap values back to initial value range.
    -endif
  -endl -done -v +

_colormap : # Implementation of the median-cut algorithm.
  -repeat {$1-1}
    @#,{s} -repeat {@#-1} # Compute box variances along all axes and find highest one.
      n=$> -repeat @{$n,s} -sh[$n] $>,$> -=[-2] {iv},$n,$> -rm[-1] -done
    -done
    c=@{-1,C}
    b=@{-arg\ 1,$c}  # Indice of boxe with highest variance.
    a=@{-arg\ 2,$c}  # Indice of axe with highest variance inside box 'b'.
    -rm[-1] -shift[$b] 0,0,0,{-$a},2 -sort[$b] +,x -shift[$b] 0,0,0,$a,2 -s[$b] x,2 # Split selected box along its median axis.
  -done
  -r 1,1,1,100%,2 -a x # Average value in each box and append as final colormap.

#@gmic direction2rgb
#@gmic : Compute RGB representation of selected 2d direction fields.
#@gmic : $ image.jpg -luminance -gradient -append c -blur 2 -orientation --direction2rgb
direction2rgb :
  -e[^-1] "Compute RGB representation of 2d direction field$?."
  -v - -channels 0,1 -repeat @#
    -s[-1] c -complex2polar[-2,-1] -round[-2] 0.001
    -*[-1] {180/pi} -%[-1] 360 100%,100%,1,1,1 -mv[-3] @#
    -if {im!=iM} -n[-1] 0,1 -else -f[-1] 1 -endif
    -a[-3--1] c -hsv2rgb[-1]
  -mv[-1] 0 -done -v +

#@gmic ditheredbw
#@gmic : Create dithered B&W version of selected images.
#@gmic : $ image.jpg --equalize 256 -ditheredbw[-1]
ditheredbw :
  -e[^-1] "Create dithered B&W version of image$?."
  -v - -repeat @#
    -n[-1] 0,255 -r[-1] 100%,100%,100%,3 2,1,1,3,0,255 -index[-2] [-1],1,1 -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic fc : eq. to '-fill_color'.
fc :
  -_fill_color $*

#@gmic fill_color : col1,...,colN
#@gmic : Fill selected images with specified color.
#@gmic : (eq. to '-fc').
#@gmic : $ image.jpg --fill_color 255,0,255
fill_color :
  -_fill_color $*

_fill_color :
  -e[0--3] "Fill image$? with color (${^0})."
  -v - -repeat @#
    -repeat {s} -sh[-1] $>,$> -f[-1] {arg(1+$>,${^0})} -rm[-1] -done
  -mv[-1] 0 -done -v +

#@gmic gradient2rgb : _orientation={ 0 | 1 }
#@gmic : Compute RGB representation of 2d gradient of selected images.
#@gmic : Default value : 'orientation=0'.
#@gmic : $ image.jpg --gradient2rgb 0 -equalize[-1] 256
gradient2rgb : -check "isbool(${1=0})"
  -if $1 -e[^-1] "Compute RGB representation of 2d gradient orientation of image$?."
  -else -e[^-1] "Compute RGB representation of 2d gradient of image$?." -endif
  -v - -repeat @#
    -norm[-1]
    -if $1 -gradient_orientation[-1] 2 -else -g[-1] xy -endif
    -a[-2,-1] c -direction2rgb[-1]
  -mv[-1] 0 -done -v +

#@gmic hsi82rgb
#@gmic : Convert selected images from HSI8 to RGB color bases.
hsi82rgb :
  -e[^-1] "Convert image$? from HSI8 to RGB color bases."
  -v - -_hsx82rgb -hsi2rgb -v +

#@gmic hsl82rgb
#@gmic : Convert selected images from HSL8 to RGB color bases.
hsl82rgb :
  -e[^-1] "Convert image$? from HSL8 to RGB color bases."
  -v - -_hsx82rgb -hsl2rgb -v +

#@gmic hsv82rgb
#@gmic : Convert selected images from HSV8 to RGB color bases.
hsv82rgb :
  -e[^-1] "Convert image$? from HSV8 to RGB color bases."
  -v - -_hsx82rgb -hsv2rgb -v +

_hsx82rgb :
 -repeat @#
    -sh[$>] 0,0 -/[-1] 0.708333 -rm[-1]
    -sh[$>] 1,2 -/[-1] 255 -rm[-1]
  -done  -v +

#@gmic lab2lch
#@gmic : Convert selected images from Lab to Lch color bases.
lab2lch :
  -e[^-1] "Convert image$? from Lab to Lch color bases."
  -v - -r 100%,100%,100%,3 -repeat @#
    -s[-1] c -complex2polar[-2,-1] -a[-3--1] c
  -mv[-1] 0 -done -v +

#@gmic lab82rgb
#@gmic : Convert selected images from Lab8 to RGB color bases.
lab82rgb :
  -e[^-1] "Convert image$? from Lab8 to RGB color bases."
  -v - -repeat @#
    -sh[$>] 0,0 -/[-1] 2.55 -rm[-1]
    -sh[$>] 1,1 -/[-1] 1.275 --[-1] 100 -rm[-1]
    -sh[$>] 2,2 -/[-1] 1.15909 --[-1] 110 -rm[-1]
  -done -lab2rgb -v +

#@gmic lch2lab
#@gmic : Convert selected images from Lch to Lab color bases.
lch2lab :
  -e[^-1] "Convert image$? from Lch to Lab color bases."
  -v - -r 100%,100%,100%,3 -repeat @#
    -s[-1] c -polar2complex[-2,-1] -a[-3--1] c
  -mv[-1] 0 -done -v +

#@gmic lch2rgb
#@gmic : Convert selected images from Lch to RGB color bases.
lch2rgb :
  -e[^-1] "Convert image$? from Lch to RGB color bases."
  -v - -lch2lab -lab2rgb -v +

#@gmic lch82rgb
#@gmic : Convert selected images from Lch8 to RGB color bases.
lch82rgb :
  -e[^-1] "Convert image$? from Lch8 to RGB color bases."
  -v - -repeat @#
    -sh[$>] 0,0 -/[-1] 2.55 -rm[-1]
    -sh[$>] 1,1 -/[-1] 1.88889 -rm[-1]
    -sh[$>] 2,2 -/[-1] 40.5845 --[-1] 3.14159 -rm[-1]
  -done -lch2rgb -v +

#@gmic luminance
#@gmic : Compute luminance of selected images.
#@gmic : $ image.jpg --luminance
luminance :
  -e[^-1] "Compute luminance of image$?."
  -v - -to_rgb -rgb2ycbcr -channels 0 -v +

#@gmic mix_rgb : a11,a12,a13,a21,a22,a23,a31,a32,a33
#@gmic : Apply 3x3 specified matrix to RGB colors of selected images.
#@gmic : Default values : 'a11=1', 'a12=a13=a21=0', 'a22=1', 'a23=a31=a32=0' and 'a33=1'.
#@gmic : $ image.jpg --mix_rgb 0,1,0,1,0,0,0,0,1
mix_rgb : -skip ${1=1},${2=0},${3=0},${4=0},${5=1},${6=0},${7=0},${8=0},${9=1}
  -e[^-1] "Apply matrix [ $1 $2 $3 ; $4 $5 $6 ; $7 $8 $9 ] to RGB colors of image$?."
  -v - -repeat @#
    -r[-1] 100%,100%,1,3,0,2 -s[-1] c
    --*[-3] $4 --*[-3] $5 -+[-1,-2] --*[-2] $6 -+[-1,-2]
    --*[-4] $7 --*[-4] $8 -+[-1,-2] --*[-3] $9 -+[-1,-2]
    -*[-5] $1 -*[-4] $2 -*[-3] $3 -+[-5--3] -a[-3--1] c
  -mv[-1] 0 -done -v +

#@gmic remove_opacity
#@gmic : Remove opacity channel of selected images.
remove_opacity :
  -e[^-1] "Remove opacity channel of image$?."
  -v - -repeat @#
    -if {s==2} -channels[-1] 0,0
    -elif {s==4} -channels[-1] 0,2
    -endif
  -mv[-1] 0 -done -v +

#@gmic replace_color : tolerance[%]>=0,_smoothness[%]>=0,src1,...,srcN,dest1,...,destN
#@gmic : Replace pixels from/to specified colors in selected images.
#@gmic : $ image.jpg --replace_color 40,3,204,153,110,255,0,0
replace_color :
  -v - (${3--1}) -y[-1] c -s[-1] c,2
  -v + -e[^-1] "Replace color ("@-2") to color ("@-1") in image$?, with tolerance $1 and smoothness $2." -v -
  -rm[-2,-1] -repeat @#
    (${3--1}) -y[-1] c -s[-1] c,2 -r[-2,-1] 1,1,1,@{-3,s} --[-1] [-2]
    -r[-2] [-3] --[-2] [-3] -norm[-2] -t[-2] {$1+1e-8} -b[-2] $2 -*[-2] -1 -+[-2] 1
    -mv[-2] @# -r[-2] [-1],[-1] -*[-2,-1] -+[-2,-1]
  -mv[-1] 0 -done -v +

#@gmic rgb2bayer : _start_pattern=0,_color=0
#@gmic : Transform selected color images to RGB-Bayer sampled images.
#@gmic : Default values : 'start_pattern=0' and 'color=0'.
#@gmic : $ image.jpg --rgb2bayer 0
rgb2bayer : -skip ${1=0},${2=0}
  -if $2 -e[^-1] "Transform image$? to a RGB-Bayer color grid, starting from pattern '$1'."
  -else -e[^-1] "Transform image$? to a RGB-Bayer monochrome grid, starting from pattern '$1'."
  -endif
  -v - -to_rgb -repeat @#
    -_rgb2bayer$1 -r[-1] [-2],0,2 -*[-2,-1]
    -if $2 -else -s[-1] c -+[-3--1] -endif
  -mv[-1] 0 -done -v +

_rgb2bayer0 : (1,0;0,0^0,1;1,0^0,0;0,1)
_rgb2bayer1 : (0,0;0,1^0,1;1,0^1,0;0,0)
_rgb2bayer2 : (0,0;1,0^1,0;0,1^0,1;0,0)
_rgb2bayer3 : (0,1;0,0^1,0;0,1^0,0;1,0)

#@gmic rgb2hsi8
#@gmic : Convert selected images from RGB to HSI8 color bases.
#@gmic : $ image.jpg -rgb2hsi8 -split c
rgb2hsi8 :
  -e[^-1] "Convert image$? from RGB to HSI8 color bases."
  -v - -rgb2hsi -_rgb2hsx8 -v +

#@gmic rgb2hsl8
#@gmic : Convert selected images from RGB to HSL8 color bases.
#@gmic : $ image.jpg -rgb2hsl8 -split c
rgb2hsl8 :
  -e[^-1] "Convert image$? from RGB to HSL8 color bases."
  -v - -rgb2hsl -_rgb2hsx8 -v +

#@gmic rgb2hsv8
#@gmic : Convert selected images from RGB to HSV8 color bases.
#@gmic : $ image.jpg -rgb2hsv8 -split c
rgb2hsv8 :
  -e[^-1] "Convert image$? from RGB to HSV8 color bases."
  -v - -rgb2hsv -_rgb2hsx8 -v +

_rgb2hsx8 :
  -repeat @#
    -sh[$>] 0,0 -*[-1] 0.708333 -rm[-1]
    -sh[$>] 1,2 -*[-1] 255 -rm[-1]
  -done

#@gmic rgb2lab8
#@gmic : Convert selected images from RGB to Lab8 color bases.
#@gmic : $ image.jpg -rgb2lab8 -split c
rgb2lab8 :
  -e[^-1] "Convert image$? from RGB to Lab8 color bases."
  -v - -rgb2lab -repeat @#
    -sh[$>] 0,0 -*[-1] 2.55 -rm[-1]
    -sh[$>] 1,1 -+[-1] 100 -*[-1] 1.275 -rm[-1]
    -sh[$>] 2,2 -+[-1] 110 -*[-1] 1.15909 -rm[-1]
  -done -v +

#@gmic rgb2lch
#@gmic : Convert selected images from RGB to Lch color bases.
#@gmic : $ image.jpg -rgb2lch -split c
rgb2lch :
  -e[^-1] "Convert image$? from RGB to Lch color bases."
  -v - -rgb2lab -lab2lch -v +

#@gmic rgb2lch8
#@gmic : Convert selected images from RGB to Lch8 color bases.
#@gmic : $ image.jpg -rgb2lch8 -split c
rgb2lch8 :
  -e[^-1] "Convert image$? from RGB to Lch8 color bases."
  -v - -rgb2lch -repeat @#
    -sh[$>] 0,0 -*[-1] 2.55 -rm[-1]
    -sh[$>] 1,1 -*[-1] 1.88889 -rm[-1]
    -sh[$>] 2,2 -+[-1] 3.14159 -*[-1] 40.5845 -rm[-1]
  -done -v +

#@gmic rgb2xyz8
#@gmic : Convert selected images from RGB to XYZ8 color bases.
#@gmic : $ image.jpg -rgb2xyz8 -split c
rgb2xyz8 :
  -e[^-1] "Convert image$? from RGB to XYZ8 color bases."
  -v - -rgb2xyz -repeat @#
    -sh[$>] 0,0 -*[-1] 255 -rm[-1]
    -sh[$>] 1,1 -*[-1] 255 -rm[-1]
    -sh[$>] 2,2 -*[-1] 231.8182 -rm[-1]
  -done -v +

#@gmic rgb2yuv8
#@gmic : Convert selected images from RGB to YUV8 color bases.
#@gmic : $ image.jpg -rgb2yuv8 -split c
rgb2yuv8 :
  -e[^-1] "Convert image$? from RGB to YUV8 color bases."
  -v - -rgb2yuv -repeat @#
    -sh[$>] 0,0 -*[-1] 255 -rm[-1]
    -sh[$>] 1,1 -+[-1] 0.44 -*[-1] 289.773 -rm[-1]
    -sh[$>] 2,2 -+[-1] 0.62 -*[-1] 205.645 -rm[-1]
  -done -v +

#@gmic select_color : tolerance[%]>=0,col1,..,colN
#@gmic : Select pixels with specified color in selected images.
#@gmic : $ image.jpg --select_color 40,204,153,110
select_color : -skip ${1=0}
  -e[^-1] "Select color (${2--1}) in image$?, with tolerance $1."
  -v - -repeat @#
    (${2--1}) -y[-1] c -r[-1] [-2] --[-2,-1] -norm[-1] -t[-1] $1 -==[-1] 0
  -mv[-1] 0 -done -v +

#@gmic sepia
#@gmic : Apply sepia tones effect on selected images.
#@gmic : $ image.jpg --sepia
sepia :
  -e[^-1] "Apply sepia tones effect on image$?."
  -v - -luminance (0,44,115,143,196,244^0,20,84,119,184,235^0,5,44,73,144,200)
  -r[-1] 256,1,1,3,3 -map[0--2] [-1] -rm[-1] -v +

#@gmic solarize
#@gmic : Solarize selected images.
#@gmic : $ image.jpg --solarize
solarize :
  -e[^-1] "Solarize image$?."
  -v - -luminance -n 0,128 -map 1 -v +

#@gmic split_opacity
#@gmic : Split color and opacity parts of selected images.
split_opacity :
  -e[^-1] "Split color and opacity parts of image$?."
  -v - -repeat @#
    -if {s==2} -s[-1] c -mv[-2,-1] 0
    -elif {s==4} --channels[-1] 3,3 -channels[-2] 0,2 -mv[-2,-1] 0
    -else -mv[-1] 0
    -endif
  -done -v +

#@gmic to_a
#@gmic : Force selected images to have an alpha channel.
to_a :
  -e[^-1] "Force image$? to have an alpha channel."
  -v - -repeat @#
    -if {s==1||s==3} -channels[-1] 0,{s} -sh[-1] {s-1},{s-1} -f[-1] 255 -rm[-1] -endif
  -mv[-1] 0 -done -v +

#@gmic to_colormode : mode={ 0=adaptive | 1=G | 2=GA | 3=RGB | 4=RGBA }
#@gmic : Force selected images to be in a given color mode.
#@gmic : Default value : 'mode=0'.
to_colormode : -skip ${1=0}
  -if {$1==1} -to_gray
  -elif {$1==2} -to_graya
  -elif {$1==3} -to_rgb
  -elif {$1==4} -to_rgba
  -else
    s=1 -repeat @#
      -if {@{$>,s}>4} -error "Image ["$>"] is not a G,GA,RGB or RGBA image."
      -else s={max($s,@{$>,s})}
      -endif
    -done -to_colormode $s
  -endif

#@gmic to_gray
#@gmic : Force selected images to be in GRAY mode.
#@gmic : $ image.jpg --to_gray
to_gray :
  -e[^-1] "Force image$? to be in GRAY mode."
  -v - -repeat @#
    -if {s>4} -error[] "Image ["@{<,-1}"] is not a G,GA,RGB or RGBA image."
    -elif {s>=3} -channels[-1] 0,2 -luminance[-1]
    -elif {s==2} -r[-1] 100%,100%,100%,1,0
    -endif
  -mv[-1] 0 -done -v +

#@gmic to_graya
#@gmic : Force selected images to be in GRAYA mode.
to_graya :
  -e[^-1] "Force image$? to be in GRAYA mode."
  -v - -repeat @#
    -if {s>4} -error[] "Image ["@{<,-1}"] is not a G,GA,RGB or RGBA image."
    -elif {s==4} --channels[-1] 3 -channels[-2] 0,2 -luminance[-2] -a[-2,-1] c
    -elif {s==3} -luminance[-1] -channels[-1] 0,1 -sh[-1] 1,1 -f[-1] 255 -rm[-1]
    -elif {s==1} -channels[-1] 0,1 -sh[-1] 1,1 -f[-1] 255 -rm[-1]
    -endif
  -mv[-1] 0 -done -v +

#@gmic to_rgb
#@gmic : Force selected images to be in RGB mode.
to_rgb :
   -e[^-1] "Force image$? to be in RGB mode."
   -v - -repeat @#
     -if {s>4} -error[] "Image ["@{<,-1}"] is not a G,GA,RGB or RGBA image."
     -elif {s==4} -channels[-1] 0,2
     -elif {s==2} -channels[-1] 0,0 -r[-1] 100%,100%,100%,3
     -elif {s==1} -r[-1] 100%,100%,100%,3
     -endif
   -mv[-1] 0 -done -v +

#@gmic to_rgba
#@gmic : Force selected images to be in RGBA mode.
to_rgba :
   -e[^-1] "Force image$? to be in RGBA mode."
   -v - -repeat @#
     -if {s>4} -error[] "Image ["@{<,-1}"] is not a G,GA,RGB or RGBA image."
     -elif {s==3} -channels[-1] 0,3 -sh[-1] 3,3 -f[-1] 255 -rm[-1]
     -elif {s==2} -r[-1] 100%,100%,100%,4 -sh[-1] 2,2 -f[-1] [-2] -rm[-1]
     -elif {s==1} -r[-1] 100%,100%,100%,4 -sh[-1] 3,3 -f[-1] 255 -rm[-1]
     -endif
   -mv[-1] 0 -done -v +

#@gmic transfer_colors : _transfer_brightness={ 0 | 1 }
#@gmic : Transfer colors of the first selected image to the other ones.
#@gmic : Default value : 'transfer_brightness=0'.
#@gmic : $ image.jpg --rand 0,255 -reverse --transfer_colors 1
transfer_colors : -skip ${1=0}
  -e[^-1] "Transfer colors of image [0] to image$?."
  -if {@#<2} -return -endif
  -v - -to_rgb[0] -to_colormode[1--1] {max(3,@{-max_s})} -c 0,255    # Convert all images to RGB[A]
  -repeat @# -sh[$>] 0,2 -rgb2ycbcr[-1] -rm[-1] -done                # Perform RGB[A] to YCbCr[A] conversion.
  -l[0] -s c -histogram_cumul 256,1,0,255 -a c -* 255 -endl          # Compute channel-by-channel cumulative histogram of target image.
  -repeat {@#-1} -l[0,-1]
    -if $1 -repeat 3 -sh[0,1] $>,$> -equalize[-1] 256,0,255 -index[-1] [-2],0,0 -rm[-2,-1] -done         # Transfer brightness + colors.
    -else -repeat 2 -sh[0,1] {$>+1},{$>+1} -equalize[-1] 256,0,255 -index[-1] [-2],0,0 -rm[-2,-1] -done  # Transfer colors only.
    -endif
  -endl -mv[-1] 1 -done -rm[0]
  -repeat @# -sh[$>] 0,2 -ycbcr2rgb[-1] -rm[-1] -done                # Perform YCbCr[A] to RGB[A] conversion.
  -v +

_transfer_colors :  # Check transfer_colors performance.
  -repeat @# -l[$>] -rgb2ycbcr -s c -histogram 256,0,255 -a c -dg 300,200 -endl -done

#@gmic xyz82rgb
#@gmic : Convert selected images from XYZ8 to RGB color bases.
xyz82rgb :
  -e[^-1] "Convert image$? from XYZ8 to RGB color bases."
  -v - -repeat @#
    -sh[$>] 0,0 -/[-1] 255 -rm[-1]
    -sh[$>] 1,1 -/[-1] 255 -rm[-1]
    -sh[$>] 2,2 -/[-1] 231.8182 -rm[-1]
  -done -xyz2rgb -v +

#@gmic yuv82rgb
#@gmic : Convert selected images from YUV8 to RGB color bases.
yuv82rgb :
  -e[^-1] "Convert image$? from YUV8 to RGB color bases."
  -v - -repeat @#
    -sh[$>] 0,0 -/[-1] 255 -rm[-1]
    -sh[$>] 1,1 -/[-1] 289.773 --[-1] 0.44 -rm[-1]
    -sh[$>] 2,2 -/[-1] 205.645 --[-1] 0.62 -rm[-1]
  -done -yuv2rgb -v +

#---------------------------------
#
#@gmic :: Geometry manipulation
#
#---------------------------------

#@gmic append_tiles : M>0,_N>0
#@gmic : Append MxN selected tiles as a new image.
append_tiles : -skip $1,${2=$1}
  -e[^-1] "Append $1x$2 tile$? as new image(s)."
  -v - -repeat {int(@#/($1*$2))} -l[{-$1*$2}--1]
    -repeat $2 -a[-$1--1] x -mv[-1] 0 -done -a y
  -endl -mv[-1] 0 -done -v +

#@gmic elevate : _depth,_is_plain,_is_colored
#@gmic : Elevate selected 2d images into 3d volumes.
#@gmic : Default values : 'depth=64', 'is_plain=1' and 'is_colored=1'.
elevate : -check "${1=64}>0" -skip ${2=1},${3=1}
  -e[^-1] "Elevate 2d image$? into $1-slices volume(s)."
  -v - -r 100%,100%,1,100%
  -repeat @# -l[-1]
  --norm[0] -i 100%,100%,$1,{if($3,@{0,s},1)}
    m=@{-2,m} d={@{-2,M}-$m}
    -repeat $1
      -if $2
        --t[1] {$m+$d*($>+1)/$1}
      -else
        --t2[1] {$m+$d*$>/$1},{$m+$d*($>+1)/$1}
      -endif
      -r[-1] 100%,100%,1,[-2] -if $3 -*[-1] [0] -endif
      -j[-2] [-1],0,0,$> -rm[-1]
    -done
  -rm[0,1] -endl -mv[-1] 0 -done -v +

#@gmic expand_x : size_x>=0,_boundary={ 0=dirichlet | 1=neumann | 2=cyclic }
#@gmic : Expand selected images along the X-axis.
#@gmic : Default value : 'border=1'.
#@gmic : $ image.jpg -expand_x 30,0
expand_x : -check "$1>=0 && ${2=1}>=0 && $2<=2"
  -e[^-1] "Expand image$? along the X-axis with size $1 and border conditions $2."
  -v - -repeat @# -r[-1] {w+2*$1},100%,100%,100%,0,$2,0.5,0.5,0.5 -mv[-1] 0 -done -v +

#@gmic expand_xy : size>=0,_boundary={ 0=dirichlet | 1=neumann | 2=cyclic }
#@gmic : Expand selected images along the XY-axes.
#@gmic : Default value : 'border=1'.
#@gmic : $ image.jpg -expand_xy 30,0
expand_xy : -check "$1>=0 && ${2=1}>=0 && $2<=2"
  -e[^-1] "Expand image$? along the XY-axes with size $1 and border conditions $2."
  -v - -repeat @# -r[-1] {w+2*$1},{h+2*$1},100%,100%,0,$2,0.5,0.5,0.5 -mv[-1] 0 -done -v +

#@gmic expand_xyz : size>=0,_boundary={ 0=dirichlet | 1=neumann | 2=cyclic }
#@gmic : Expand selected images along the XYZ-axes.
#@gmic : Default value : 'border=1'.
expand_xyz : -check "$1>=0 && ${2=1}>=0 && $2<=2"
  -e[^-1] "Expand image$? along the XYZ-axes with size $1 and border conditions $2."
  -v - -repeat @# -r[-1] {w+2*$1},{h+2*$1},{d+2*$1},100%,0,$2,0.5,0.5,0.5 -mv[-1] 0 -done -v +

#@gmic expand_y : size_y>=0,_boundary={ 0=dirichlet | 1=neumann | 2=cyclic }
#@gmic : Expand selected images along the Y-axis.
#@gmic : Default value : 'border=1'.
#@gmic : $ image.jpg -expand_y 30,0
expand_y : -check "$1>=0 && ${2=1}>=0 && $2<=2"
  -e[^-1] "Expand image$? along the Y-axis with size $1 and border conditions $2."
  -v - -repeat @# -r[-1] 100%,{h+2*$1},100%,100%,0,$2,0.5,0.5,0.5 -mv[-1] 0 -done -v +

#@gmic expand_z : size_z>=0,_boundary={ 0=dirichlet | 1=neumann | 2=cyclic }
#@gmic : Expand selected images along the Z-axis.
#@gmic : Default value : 'border=1'.
expand_z : -check "$1>=0 && ${2=1}>=0 && $2<=2"
  -e[^-1] "Expand image$? along the Z-axis with size $1 and border conditions $2."
  -v - -repeat @# -r[-1] 100%,100%,{d+2*$1},100%,0,$2,0.5,0.5,0.5 -mv[-1] 0 -done -v +

#@gmic rr2d : eq. to '-resize_ratio2d'.
rr2d :
  -_resize_ratio2d $*

#@gmic resize_ratio2d : width>0,height>0,_mode={ 0=inside | 1=outside | 2=padded },0=<_interpolation<=6
#@gmic : Resize selected images while preserving their aspect ratio.
#@gmic : (eq. to '-rr2d').
#@gmic : Default values : 'mode=0' and 'interpolation=6'.
resize_ratio2d :
  -_resize_ratio2d $*

_resize_ratio2d : -check "$1>0 && $2>0 && ${3=0}>=0 && $3<=2 && ${4=6}>=0 && $4<=6"
  -e[0--3] "Resize 2d image$? to $1x$2 with ratio-"\
           @{"-if {$3==0} -u inside -elif {$3==1} -u outside -else -u padded -endif"}\
           " mode and interpolation type $4."
  -v - -repeat @#
    -if {$3==0}   ratio={min($1/w,$2/h)}
    -elif {$3==1} ratio={max($1/w,$2/h)}
    -else         ratio={min($1/w,$2/h)}
    -endif
    -r[-1] {w*$ratio},{h*$ratio},100%,100%,$4
    -if {$3==2} -r[-1] $1,$2,100%,100%,0,0,0.5,0.5 -endif
  -mv[-1] 0 -done -v +

#@gmic r2dx : eq. to '-resize2dx'.
r2dx :
  -_resize2dx $*

#@gmic resize2dx : width>0,_interpolation={0,1,2,3,4,5,6}
#@gmic : Resize selected images along the X-axis, preserving 2d ratio.
#@gmic : (eq. to '-r2dx').
#@gmic : Default value : 'interpolation=2'.
#@gmic : $ image.jpg --resize2dx 100,2 -append x
resize2dx :
  -_resize2dx $*

_resize2dx : -check "$1>0 && ${2=2}>=0 && $2<=6"
  -e[0--3] "Resize 2d image$? to $1 pixels along the X-axis, preserving 2d ratio."
  -v - -repeat @#
    -r[-1] $1,{max(1,h*$1/w)},100%,100%,$2
  -mv[-1] 0 -done -v +

#@gmic r2dy : eq. to '-resize2dy'.
r2dy :
  -_resize2dy $*

#@gmic resize2dy : height>0,_interpolation={0,1,2,3,4,5,6}
#@gmic : Resize selected images along the Y-axis, preserving 2d ratio.
#@gmic : (eq. to '-r2dy').
#@gmic : Default value : 'interpolation=2'.
#@gmic : $ image.jpg --resize2dy 100,2 -append x
resize2dy :
  -_resize2dy $*

_resize2dy : -check "$1>0 && ${2=2}>=0 && $2<=6"
  -e[0--3] "Resize 2d image$? to $1 pixels along the Y-axis, preserving 2d ratio."
  -v - -repeat @#
    -r[-1] {max(1,w*$1/h)},$1,100%,100%,$2
  -mv[-1] 0 -done -v +

#@gmic r3dx : eq. to '-resize3dx'.
r3dx :
  -_resize3dx $*

#@gmic resize3dx : width>0,_interpolation={0,1,2,3,4,5,6}
#@gmic : Resize selected images along the X-axis, preserving 3d ratio.
#@gmic : (eq. to '-r3dx').
#@gmic : Default value : 'interpolation=2'.
resize3dx :
  -_resize3dx $*

_resize3dx : -check "$1>0 && ${2=2}>=0 && $2<=6"
  -e[0--3] "Resize 3d image$? to $1 pixels along the X-axis, preserving 3d ratio."
  -v - -repeat @#
    -r[-1] $1,{max(1,h*$1/w)},{max(1,d*$1/w)},100%,$2
  -mv[-1] 0 -done -v +

#@gmic r3dy : eq. to '-resize3dy'.
r3dy :
  -_resize3dy $*

#@gmic resize3dy : height>0,_interpolation={0,1,2,3,4,5,6}
#@gmic : Resize selected images along the Y-axis, preserving 3d ratio.
#@gmic : (eq. to '-r3dy').
#@gmic : Default value : 'interpolation=2'.
resize3dy :
  -_resize3dy $*

_resize3dy : -check "$1>0 && ${2=2}>=0 && $2<=6"
  -e[0--3] "Resize 3d image$? to $1 pixels along the Y-axis, preserving 3d ratio."
  -v - -repeat @#
    -r[-1] {max(1,w*$1/h)},$1,{max(1,d*$1/h)},100%,$2
  -mv[-1] 0 -done -v +

#@gmic r3dz : eq. to '-resize3dz'.
r3dz :
  -_resize3dz $*

#@gmic resize3dz : depth>0,_interpolation={0,1,2,3,4,5,6}
#@gmic : Resize selected images along the Z-axis, preserving 3d ratio.
#@gmic : (eq. to '-r3dz').
#@gmic : Default value : 'interpolation=2'.
resize3dz :
  -_resize3dz $*

_resize3dz : -check "$1>0 && ${2=2}>=0 && $2<=6"
  -e[0--3] "Resize 3d image$? to $1 pixels along the Z-axis, preserving 3d ratio."
  -v - -repeat @#
    -r[-1] {max(1,w*$1/d)},{max(1,h*$1/d)},$1,100%,$2
  -mv[-1] 0 -done -v +

#@gmic rotate_tileable : angle,_max_size_factor>=0
#@gmic : Rotate selected images by specified angle and make them tileable.
#@gmic : If resulting size of an image is too big, the image is replaced by a 1x1 image.
#@gmic : Default values : 'max_size_factor=8'.
rotate_tileable : -check ${2=8}>=0
  -e[^-1] "Rotate image$? with angle $1° and make them tileable."
  -v -

  # Reduce angle to known fraction.
  angle={$1%360}
  -if {$angle>=270} -rotate 270 angle={$angle-270}
  -elif {$angle>=180} -rotate 180 angle={$angle-180}
  -elif {$angle>=90} -rotate 90 angle={$angle-90}
  -endif
  (0,1;1,8;1,7;1,6;1,5;1,4;1,5;1,3;2,5;1,2;2,5;3,5;2,3;3,4;4,5;1,1;5,4;7,5;3,2;8,5;9,5;2,1;3,1;4,1;5,1;6,1;7,1;8,1) # List of known fractions.
  -s[-1] x,2 --/[-2,-1] -atan[-1] -*[-1] {180/pi}         # Compute corresponding angles.
  ($angle) -index[-1] [-2] -rm[-2]
  p=@{-3,@-1} q=@{-2,@-1} -rm[-3--1]                      # Find nearest fraction p/q to atan(angle).
  -if {!$p||!$q} -return -endif

  -repeat @#
    # Compute width and height of tile.
    theta={atan2($p,$q)}
    gcd=@{-gcd" "{h*$q},{w*$p}}
    pw={h*$q/$gcd}
    nw={round($pw*w/cos($theta))}
    gcd=@{-gcd" "{h*$p},{w*$q}}
    qh={w*$q/$gcd}
    nh={round($qh*h/cos($theta))}

    # Rotate and make tileable (may result in very large images !).
    -if {!$2" || "($nw<$2*w" && "$nh<$2*h)}
      -r[-1] {1.5*$nw},{1.5*$nh},1,100%,0,2
      -rotate[-1] {$theta*180/pi},2,1,50%,50%
      -r[-1] $nw,$nh,1,100%,0,2,0.5,0.5
    -else -rm[-1] 1
    -endif
  -mv[-1] 0 -done -v +

#@gmic rows : eq. to '-lines'.
rows : -skip ${2=$1}
  -e[^-1] "Keep line"@{"-if {$1==$2} -u \" $1\" -else -u \"s $1..$2\" -endif"}" of image$?."
  -v - -lines $* -v +

#@gmic shrink_x : size_x>=0
#@gmic : Shrink selected images along the X-axis.
#@gmic : $ image.jpg -shrink_x 30
shrink_x : -check "$1>=0"
  -e[^-1] "Shrink image$? along the X-axis with size $1."
  -v - -repeat @# -z[-1] $1,{w-$1-1} -mv[-1] 0 -done -v +

#@gmic shrink_xy : size>=0
#@gmic : Shrink selected images along the XY-axes.
#@gmic : $ image.jpg -shrink_xy 30
shrink_xy : -check "$1>=0"
  -e[^-1] "Shrink image$? along the XY-axes with size $1."
  -v - -repeat @# -z[-1] $1,$1,{w-$1-1},{h-$1-1} -mv[-1] 0 -done -v +

#@gmic shrink_y : size_y>=0
#@gmic : Shrink selected images along the Y-axis.
#@gmic : $ image.jpg -shrink_y 30
shrink_y : -check "$1>=0"
  -e[^-1] "Shrink image$? along the Y-axis with size $1."
  -v - -repeat @# -z[-1] 0,$1,100%,{h-$1-1} -mv[-1] 0 -done -v +

#@gmic shrink_z : size_z>=0
#@gmic : Shrink selected images along the Z-axis.
shrink_z : -check "$1>=0"
  -e[^-1] "Shrink image$? along the Z-axis with size $1."
  -v - -repeat @# -z[-1] 0,0,$1,100%,100%,{d-$1-1} -mv[-1] 0 -done -v +

#@gmic split_tiles : M!=0,_N!=0,_is_homogeneous={ 0 | 1 }
#@gmic : Split selected images as a MxN array of tiles.
#@gmic : Default values : 'N=M' and 'is_homogeneous=0'.
#@gmic : $ image.jpg --local -split_tiles 5,4 -blur 3,0 -sharpen 700 -append_tiles 4,5 -endlocal
split_tiles : -skip ${2=$1},${3=0}
  -if $3 -e[^-1] "Split image$? as a $1x$2 array of homogeneous tiles."
  -else -e[^-1] "Split image$? as a $1x$2 array of tiles."
  -endif
  -v - -repeat @#
    -l[-1] -s y,$2 -s x,$1 -if $3 -r [0],[0],100%,100%,0 -endif -endl
  -mv[{-$1*$2}--1] 0 -done -v +

#@gmic upscale_smart : width,_height,_depth,_smoothness>=0,_anisotropy=[0,1],sharpening>=0
#@gmic : Upscale selected images with an edge-preserving algorithm.
#@gmic : Default values : 'height=100%', 'depth=100%', 'smoothness=2', 'anisotropy=0.4' and 'sharpening=10'.
#@gmic : $ image.jpg -resize2dy 100 --upscale_smart 500%,500% -append x
upscale_smart : -skip ${2=100%},${3=100%} -check "${4=2}>=0 && ${5=0.4}>=0 && $5<=1 && ${6=10}>=0"
  -e[^-1] "Upscale image$? to $1x$2x$3, with smoothness $4, anisotropy $5 and sharpening $6."
  -v - -repeat @#
    w={w} h={h}
    --r[-1] $1,$2,$3,1,0  # Compute desired dimensions.
    -if {w<$w" && "h<$h}  # Test for downscaling
      -rm[-1] -r[-1] $1,$2,$3,100%,2
    -else
      -rm[-1] --diffusiontensors 0,$5,1.2,1.2
      -r[-2,-1] $1,$2,$3,100%,5
      -smooth[-2] [-1],$4 -rm[-1]
      -apply_channels "-sharpen[-1] $6,10",3,0
    -endif
  -mv[-1] 0 -done -v +

#---------------------------------
#
#@gmic :: Filtering
#
#---------------------------------

#@gmic bandpass : _min_freq[%],_max_freq[%]
#@gmic : Apply bandpass filter to selected images.
#@gmic : Default values : 'min_freq=0' and 'max_freq=20%'.
#@gmic : $ image.jpg -bandpass 1%,3%
bandpass : -skip ${1=0},${2=20%}
  -e[^-1] "Apply bandpass filter [$1,$2] to image$?."
  -v - -repeat @#
    100%,100%,100% -f[-1] "sqrt((x/w-0.5)^2 + (y/h-0.5)^2 + (z/d-0.5)^2)" -n[-1] 0,1 -t2[-1] $1,$2 -shift[-1] {int(w/2)},{int(h/2)},50%,0,2
    -fft[-2] -*[-3] [-1] -*[-2,-1] -ifft[-2,-1] -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic blur_angular : amplitude[%],_cx,_cy
#@gmic : Apply angular blur on selected images.
#@gmic : Default values : 'cx=cy=0.5'.
#@gmic : $ image.jpg --blur_angular 2%
blur_angular : -skip ${2=0.5},${3=0.5}
  -e[^-1] "Apply angular blur on image$?, with amplitude $1 and center ($2,$3)."
  -v - -euclidean2polar $2,$3,1.3,1 -expand_y 16,2 -blur_y $1 -shrink_y 16 -polar2euclidean $2,$3,1.3,1 -v +

#@gmic blur_linear : amplitude1[%],_amplitude2[%],_angle,_boundary={ 0=dirichlet | 1=neumann }
#@gmic : Apply linear blur on selected images, with specified angle and amplitudes.
#@gmic : Default values : 'amplitude2=0', 'angle=0' and 'boundary=1'.
#@gmic : $ image.jpg --blur_linear 10,0,45
blur_linear : -skip ${2=0},${3=0},${4=1}
  -e[^-1] "Apply linear blur on image$?, with angle $3° and amplitudes ($1,$2)."
  -v -
  -if {isval($1)} std1=$1 -else std1={(${1}10000)*max(w,h)/100} -endif
  -if {isval($2)} std2=$2 -else std2={(${2}10000)*max(w,h)/100} -endif
  stdM={round(1.25*max($std1,$std2))}
  -if {$stdM<=0} -return -endif
  -repeat @#
    -if {$4==1} -expand_xy[-1] $stdM,1 -else -expand_xy[-1] $stdM,0 -endif
    {2*$stdM},{2*$stdM} -gaussian[-1] $1,$2,$3 -normalize_sum[-1]
    -convolve_fft[-2,-1] -shrink_xy[-1] $stdM
  -mv[-1] 0 -done -v +

#@gmic blur_radial : amplitude[%],_cx,_cy
#@gmic : Apply radial blur on selected images.
#@gmic : Default values : 'cx=cy=0.5'.
#@gmic : $ image.jpg --blur_radial 2%
blur_radial : -skip ${2=0.5},${3=0.5}
  -e[^-1] "Apply radial blur on image$?, with amplitude $1 and center ($2,$3)."
  -v - -euclidean2polar $2,$3,5,1 -blur_x $1 -polar2euclidean $2,$3,5,1 -v +

#@gmic blur_x : amplitude[%]>=0,_boundary={ 0=dirichlet | 1=neumann }
#@gmic : Blur selected images along the X-axis.
#@gmic : Default value : 'boundary=1'.
#@gmic : $ image.jpg --blur_x 6
blur_x : -skip ${2=1}
  -deriche $1,0,x,$2

#@gmic blur_xy : amplitude_x[%],amplitude_y[%],_boundary={ 0=dirichlet | 1=neumann }
#@gmic : Blur selected images along the X and Y axes.
#@gmic : Default value : 'boundary=1'.
#@gmic : $ image.jpg --blur_xy 6
blur_xy : -skip ${2=$1},${3=1}
  -deriche $1,0,x,$3 -deriche $2,0,y,$3

#@gmic blur_xyz : amplitude_x[%],amplitude_y[%],amplitude_z,_boundary={ 0=dirichlet | 1=neumann }
#@gmic : Blur selected images along the X, Y and Z axes.
#@gmic : Default value : 'boundary=1'.
blur_xyz : -skip ${4=1}
  -deriche $1,0,x,$4 -deriche $2,0,y,$4 -deriche $3,0,z,$4

#@gmic blur_y : amplitude[%]>=0,_boundary={ 0=dirichlet | 1=neumann }
#@gmic : Blur selected images along the Y-axis.
#@gmic : Default value : 'boundary=1'.
#@gmic : $ image.jpg --blur_y 6
blur_y : -skip ${2=1}
  -deriche $1,0,y,$2

#@gmic blur_z : amplitude[%]>=0,_boundary={ 0=dirichlet | 1=neumann }
#@gmic : Blur selected images along the Z-axis.
#@gmic : Default value : 'boundary=1'.
blur_z : -skip ${2=1}
  -deriche $1,0,z,$2

#@gmic compose_freq
#@gmic : Compose selected low and high frequency parts into new images.
#@gmic : $ image.jpg -split_freq 2% -mirror[-1] x -compose_freq
compose_freq :
  -e[^-1] "Compose low and high frequency part$? into new images."
  -v - -repeat {int(@#/2)}
    -+[-2,-1]
  -mv[-1] 0 -done -v +

#@gmic convolve_fft
#@gmic : Convolve selected images two-by-two through fourier transforms.
#@gmic : $ image.jpg 100%,100% -gaussian[-1] 20,1,45 --convolve_fft
convolve_fft :
  -e[^-1] "Convolve image$? two-by-two through fourier transforms."
  -v - -repeat {int(@#/2)} w2={int(@{-2,w}/2)} h2={int(@{-2,h}/2)} d2={int(@{-2,d}/2)}
    -r[-1] [-2],[-2],[-2],1,0,0,0.5,0.5,0.5,0.5 -shift[-1] -$w2,-$h2,-$d2,0,2
    -fft[-2] -fft[-1]
    --*[-4] [-1] --*[-4] [-3] -+[-2,-1]
    -*[-5,-3] -*[-3,-2] --[-3,-2]
    -ifft[-2,-1] -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic cross_correlation
#@gmic : Compute cross-correlation using two-by-two selected images.
#@gmic : $ image.jpg --shift -30,-20 -cross_correlation
cross_correlation :
  -e[^-1] "Compute cross-correlation using two-by-two image$?."
  -v - -repeat {int(@#/2)}
    -norm[-2,-1] -fft[-2] -fft[-1] [-2,-1] -mul[-2] [-5] -mul[-1] [-6]
    --[-2,-1] -*[-5,-3] -*[-3,-2] -+[-3,-2] -ifft[-2,-1] -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic curvature
#@gmic : Compute isophote curvatures on selected images.
#@gmic : $ image.jpg -blur 10 -curvature
curvature :
  -e[^-1] "Compute isophote curvatures on image$?."
  -v - -repeat @#
    -if {d==1}
      --g[-1] xy,0 -hessian[-3] xxxyyy                        # ixx ixy iyy ix iy
      -*[-3] [-2] -*[-4] [-1] -*[-4] -2                       # ixx -2iyixy ixiyy ix iy
      -+[-4,-3] -*[-3] [-2]                                   # ixx -2ixiyixy+ix^2iyy ix iy
      -sqr[-2,-1] -*[-4] [-1] -+[-4,-3]                       # iy^2ixx-2ixiyixy+ix^2iyy ix^2 iy^2
      -+[-2,-1] -+[-1] 0.1 -^[-1] 1.5 -/[-2,-1]               # (iy^2ixx+2ixiyixy+ix^2iyy)/(ix^2+iy^2)
    -else
      --inn[-1] --gradient_norm[-2] -laplacian[-3]            # inn+iee inn in
      --[-3,-2] -+[-1] 0.1 -/[-2,-1]                          # iee in
      --inn[-1] -laplacian[-2] --[-2,-1]                      # iee/in
    -endif
  -mv[-1] 0 -done -v +

#@gmic deinterlace : _method={ 0 | 1 }
#@gmic : Deinterlace selected images ('method' can be { 0=standard or 1=motion-compensated }).
#@gmic : Default value : 'method=0'.
#@gmic : $ image.jpg --rotate 3,1,1,50%,50% -resize 100%,50% -resize 100%,200%,1,3,4 -shift[-1] 0,1 -add --deinterlace 1
deinterlace : -skip ${1=0}
  -if $1 -e[^-1] "Deinterlace image$? with motion-compensated method."
  -else  -e[^-1] "Deinterlace image$? with standard method."
  -endif
  -v - -repeat @#
    -i[-2] ({w},{h})
    -if {$1==0}
      -l[-1] -s y -a[0--1:2] y -a[1--1] y -r[-2] [-1],0 -r[-2,-1] 100%,200%,100%,100%,5
      -+[-2,-1] -/[-1] 2 -c[-1] 0,255 -endl
    -else
      -l[-1] -s y -a[0--1:2] y -a[1--1] y -r[-2] [-1],0 -r[-2,-1] 100%,200%,1,100%,5
      --displacement[-1] [-2],0.05 -warp[-3] [-1],1,1,1 -rm[-1]
      -+[-2,-1] -/[-1] 2 -c[-1] 0,255 -endl
    -endif
    -r[-1] @-2 -rm[-2]
  -mv[-1] 0 -done -v +

#@gmic deconvolve_fft
#@gmic : Deconvolve selected images two-by-two through fourier transforms.
deconvolve_fft :
  -e[^-1] "Deconvolve image$? two-by-two through fourier transforms."
  -v - -repeat {int(@#/2)} w2={int(@{-2,w}/2)} h2={int(@{-2,h}/2)} d2={int(@{-2,d}/2)}
    -r[-1] [-2],[-2],[-2],1,0,0,0.5,0.5,0.5,0.5 -shift[-1] -$w2,-$h2,-$d2,0,2
    -fft[-2] -fft[-1]                          # a b a' b'
    --sqr[-2] --sqr[-2] -+[-2,-1] -+[-1] 1e-5  # a b a' b' (a'^2+b'^2)
    --*[-4] [-3]                               # a b a' b' (a'^2+b'^2) ba'
    --*[-6] [-3]                               # a b a' b' (a'^2+b'^2) ba' ab'
    --[-2,-1]                                  # a b a' b' (a'^2+b'^2) ba'-ab'
    -*[-6,-4]                                  # aa' b b' (a'^2+b'^2) ba'-ab'
    -*[-4,-3]                                  # aa' bb' (a'^2+b'^2) ba'-ab'
    -+[-4,-3]                                  # aa'+bb' (a'^2+b'^2) ba'-ab'
    -/[-1] [-2] -/[-3,-2]                      # divide (aa'+bb') and (ba'-ab') by (a'^2+b'^2)
    -ifft[-2,-1] -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic dilate_circ : _size>=0,_boundary,_is_normalized={ 0 | 1 }
#@gmic : Apply circular dilation of selected image by specified size.
#@gmic : Default values : 'boundary=1' and 'is_normalized=0'.
#@gmic : $ image.jpg --dilate_circ 7
dilate_circ : -check $1>=0 -skip ${2=1},${3=0}
  -e[^-1] "Apply circular dilation of image$? by size $1, boundary $2 and is_normalized $3."
  -v -
  -if {$1<2} -return -endif
  -_kr_circle $1 -dilate[^-1] [-1],$2,$3 -rm[-1] -v +

#@gmic dilate_oct : _size>=0,_boundary,_is_normalized={ 0 | 1 }
#@gmic : Apply octagonal dilation of selected image by specified size.
#@gmic : Default values : 'boundary=1' and 'is_normalized=0'.
#@gmic : $ image.jpg --dilate_oct 7
dilate_oct : -check $1>=0 -skip ${2=1},${3=0}
  -e[^-1] "Apply octagonal dilation of image$? by size $1, boundary $2 and is_normalized $3."
  -v -
  -if {$1<2} -return -endif
  -if {$1&1} ss={$1} -else ss={$1+1} -endif
  -i[0] (0,1,0;1,1,1;0,1,0) -i[1] (1,1,1;1,1,1;1,1,1)
  -repeat {@#-2}
    r={round(($ss-1)*sqrt(2)/(1+sqrt(2))/2)}
    q={round(($ss-1)/(1+sqrt(2))/2)}
    -if {$r>0} -repeat $r -dilate[-1] [0],$2,$3 -done -endif
    -if {$q>0} -repeat $q -dilate[-1] [1],$2,$3 -done -endif
  -mv[-1] 2 -done -rm[0,1] -v +

_kr_circle :
  -if {$1%2==0} -i 2,2,1,1,1 -else -i 1,1,1,1,1 -endif -r[-1] $1,$1,1,1,0,0,0.5,0.5
  -distance[-1] 1 -round[-1] 0.5 -t2[-1] 0,{$1/2}

#@gmic divergence
#@gmic : Compute divergence of selected vector fields.
#@gmic : $ image.jpg -luminance --gradient -a[-2,-1] c -divergence[-1]
divergence :
  -e[^-1] "Compute divergence of vector field$?."
  -v - -repeat @#
    -if {s==1} -g[-1] x,0
    -elif {s==2} -s[-1] c -g[-2] x,0 -g[-1] y,0 -+[-2,-1]
    -elif {s==3} -s[-1] c -g[-3] x,0 -g[-2] y,0 -g[-1] z,0 -+[-3--1]
    -else -error[] "Cannot compute divergence of image ["$>"] (has "{s}">3 channels)."
    -endif
  -mv[-1] 0 -done -v +

#@gmic dog : _sigma1>=0[%],_sigma2>=0[%]
#@gmic : Compute difference of gaussian on selected images.
#@gmic : Default values : 'sigma1=2%' and 'sigma2=3%'.
#@gmic : $ image.jpg --dog 2,3
dog : -skip ${1=2%},${2=3%}
  -e[^-1] "Compute difference of gaussian on image$?, with standard deviations $1 and $2."
  -v - -repeat @#
    --b[-1] $1 -b[-2] $2 --[-2,-1] -norm[-1]
  -mv[-1] 0 -done -v +

#@gmic edges : _threshold[%]>=0
#@gmic : Estimate contours of selected images.
#@gmic : Default value : 'edges=15%'
#@gmic : $ image.jpg --edges 15%
edges : -skip ${1=15%}
  -e[^-1] "Estimate image contours of image$?, with threshold $1."
  -v - -repeat @#
    -gradient_norm[-1] -b[-1] 0.5 -t[-1] $1 -distance[-1] 0 -equalize[-1] 256
    -negative[-1] -c[-1] 30%,70% -n[-1] 0,1
  -mv[-1] 0 -done -v +

#@gmic diffusiontensors : _sharpness>=0,0<=_anisotropy<=1,_alpha[%],_sigma[%],is_sqrt={ 0 | 1 }
#@gmic : Compute the diffusion tensors of selected images for edge-preserving smoothing algorithms.
#@gmic : Default values : 'sharpness=0.7', 'anisotropy=0.3', 'alpha=0.6', 'sigma=1.1' and 'is_sqrt=0'.
#@gmic : $ image.jpg -diffusiontensors 0.8 -abs -pow 0.2
diffusiontensors : -check "${1=0.7}>=0 && ${2=0.3}>=0 && $2<=1" -skip ${3=0.6},${4=1.1},${5=0}
  -e[^-1] "Compute diffusion tensors for image$?, with sharpness $1, anisotropy $2, alpha $3 and sigma $4."
  -v -
  p1={if($5,0.5,1)*max($1,1e-5)}
  p2={$p1/(1e-7+1-$2)}
  -b $3 -n 0,255 -structuretensors 2 -b $4
  -repeat @#
    -eigen[-1] -max[-2] 0
    -if {s==2} -s[-2] c -+[-3,-2] -+[-2] 1 --pow[-2] -$p1 -pow[-3] -$p2 -a[-3,-1] c                     # 2d
    -else -s[-2] c -+[-4--2] -+[-2] 1 --pow[-2] -$p1 -r[-1] 100%,100%,100%,2 -pow[-3] -$p2 -a[-3,-1] c  # 3d
    -endif
    -eigen2tensor[-2,-1]
  -done -v +

#@gmic erode_circ : _size>=0,_boundary,_is_normalized={ 0 | 1 }
#@gmic : Apply circular erosion of selected images by specified size.
#@gmic : Default values : 'boundary=1' and 'is_normalized=0'.
#@gmic : $ image.jpg --erode_circ 7
erode_circ : -check $1>=0 -skip ${2=1},${3=0}
  -e[^-1] "Apply circular erosion of image$? by size $1, boundary $2 and is_normalized $3."
  -v -
  -if {$1<2} -return -endif
  -_kr_circle $1 -erode[^-1] [-1],$2,$3 -rm[-1] -v +

#@gmic erode_oct : _size>=0,_boundary,_is_normalized={ 0 | 1 }
#@gmic : Apply octagonal erosion of selected images by specified size.
#@gmic : Default values : 'boundary=1' and 'is_normalized=0'.
#@gmic : $ image.jpg --erode_oct 7
erode_oct : -check $1>=0 -skip ${2=1},${3=0}
  -e[^-1] "Apply octagonal erosion of image$? by size $1, boundary $2 and is_normalized $3."
  -v -
  -if {$1<2} -return -endif
  -if {$1&1} ss={$1} -else ss={$1+1} -endif
  -i[0] (0,1,0;1,1,1;0,1,0) -i[1] (1,1,1;1,1,1;1,1,1)
  -repeat {@#-2}
    r={round(($ss-1)*sqrt(2)/(1+sqrt(2))/2)}
    q={round(($ss-1)/(1+sqrt(2))/2)}
    -if {$r>0} -repeat $r -erode[-1] [0],$2,$3 -done -endif
    -if {$q>0} -repeat $q -erode[-1] [1],$2,$3 -done -endif
  -mv[-1] 2 -done -rm[0,1] -v +

#@gmic gradient_orientation : _dimension={1,2,3}
#@gmic : Compute N-D gradient orientation of selected images.
#@gmic : Default value : 'dimension=3'.
#@gmic : $ image.jpg --gradient_orientation 2
gradient_orientation : -check "${1=3}==1 || $1==2 || $1==3"
  -e[^-1] "Compute $1-D gradient orientation of image$?."
  -v - -repeat @#
    -if {$1==1} -g[-1] x --abs[-1] -+[-1] 1e-8 -/[-2,-1]
    -elif {$1==2} -g[-1] xy --sqr[-2--1] -+[-2,-1] -+[-1] 1e-8 -sqrt[-1] -/[-3] [-1] -/[-2,-1]
    -else -g[-1] xyz --sqr[-3--1] -+[-3--1] -+[-1] 1e-8 -sqrt[-1] -/[-4,-3] [-1] -/[-2,-1]
    -endif
  -mv[-$1--1] 0 -done -v +

#@gmic gradient_norm
#@gmic : Compute gradient norm of selected images.
#@gmic : $ image.jpg --gradient_norm -equalize[-1] 256
gradient_norm :
  -e[^-1] "Compute gradient norm of image$?."
  -v - -repeat @#
    --g[-1] x -sqr[-1]
    --g[-2] y -sqr[-1] -+[-2,-1]
    -g[-2] z -sqr[-2] -+[-2,-1]
    s={s} -s[-1] c -+[-$s--1] -sqrt[-1]
  -mv[-1] 0 -done -v +

#@gmic heat_flow : _nb_iter>=0,_dt,_keep_sequence={ 0 | 1 }
#@gmic : Apply iterations of the heat flow on selected images.
#@gmic : Default values : 'nb_iter=10', 'dt=30' and 'keep_sequence=0'.
#@gmic : $ image.jpg --heat_flow 20
heat_flow : -skip ${1=10},${2=30},${3=0}
  -e[^-1] "Apply $1 iterations of the heat flow on image$?, with time step $2."
  -v - -pde_flow $1,$2,laplacian,$3 -v +

#@gmic iee
#@gmic : Compute gradient-orthogonal-directed 2nd derivative of image(s).
#@gmic : $ image.jpg -iee
iee :
  -e[^-1] "Compute gradient-orthogonal-directed 2nd derivative of image$?."
  -v - -repeat @#
    -if {d==1}
      --g[-1] xy,0 -hessian[-3] xxxyyy                        # ixx ixy iyy ix iy
      -*[-3] [-2] -*[-4] [-1] -*[-4] -2                       # ixx -2iyixy ixiyy ix iy
      -+[-4,-3] -*[-3] [-2]                                   # ixx -2ixiyixy+ix^2iyy ix iy
      -sqr[-2,-1] -*[-4] [-1] -+[-4,-3]                       # iy^2ixx-2ixiyixy+ix^2iyy ix^2 iy^2
      -+[-2,-1] -+[-1] 1e-8 -/[-2,-1]                         # (iy^2ixx+2ixiyixy+ix^2iyy)/(ix^2+iy^2)
    -else
      --inn[-1] -laplacian[-2] --[-2,-1]
    -endif
  -mv[-1] 0 -done -v +

#@gmic inn
#@gmic : Compute gradient-directed 2nd derivative of image(s).
#@gmic : $ image.jpg -inn
inn :
  -e[^-1] "Compute gradient-directed 2nd derivative of image$?."
  -v - -repeat @#
    -if {d==1}
      --g[-1] xy,0 -hessian[-3] xxxyyy                        # ixx ixy iyy ix iy
      -*[-5] [-2] -*[-4] [-1] -*[-4] 2                        # ixixx 2iyixy iyy ix iy
      -+[-5,-4] -*[-4] [-2]                                   # ix^2ixx+2ixiyixy iyy ix iy
      -sqr[-2,-1] -*[-3] [-1] -+[-4,-3]                       # ix^2ixx+2ixiyixy+iy^2iyy ix^2 iy^2
      -+[-2,-1] -+[-1] 1e-8 -/[-2,-1]                         # (ix^2ixx+2ixiyixy+iy^2iyy)/(ix^2+iy^2)
    -else
      --g[-1] xyz,0 -hessian[-4] xxxyxzyyyzzz                 # ixx ixy ixz iyy iyz izz ix iy iz
      -*[-9] [-3] -*[-8] [-2] -*[-8] 2 -*[-7] [-1] -*[-7] 2   # ixixx 2iyixy 2izixz iyy iyz izz ix iy iz
      -+[-9--7] -*[-7] [-3]                                   # ix^2ixx+2ixiyixy+2ixizixy iyy iyz izz ix iy iz
      -*[-6] [-2] -*[-5] [-1] -*[-5] 2                        # ix^2ixx+2ixiyixy+2ixizixy iyiyy 2iziyz izz ix iy iz
      -+[-6,-5] -*[-5] [-2] -+[-6,-5]                         # ix^2ixx+2ixiyixy+2ixizixy+iy^2iyy+2iyiziyz izz ix iy iz
      -sqr[-3--1] -*[-4] [-1] -+[-5,-4]                       # ix^2ixx+2ixiyixy+2ixizixy+iy^2iyy+2iyiziyz+iz^2izz ix^2 iy^2 iz^2
      -+[-3--1] -+[-1] 1e-8 -/[-2,-1]                         # (ix^2ixx+2ixiyixy+2ixizixy+iy^2iyy+2iyiziyz+iz^2izz)/(ix^2+iy^2+iz^2)
    -endif
  -mv[-1] 0 -done -v +

#@gmic inpaint_flow : _nb_iter1>=0,_nb_iter2>=0,_dt>=0,_alpha,_sigma
#@gmic : Apply iteration of the inpainting flow on selected images.
#@gmic : Default values : 'nb_iter1=4', 'nb_iter2=15', 'dt=15', 'alpha=1' and 'sigma=3'.
#@gmic : $ image.jpg 100%,100% -ellipse[-1] 30%,30%,40,30,0,1,255 -reverse -inpaint_flow ,
inpaint_flow : -skip ${1=4},${2=15},${3=15},${4=1},${5=3}
  -e[^-1] "Apply $1 iteration of the inpainting flow on image$?."
  -v - -norm[0] -quantize[0] 2 -n[0] 0,1 -repeat @# -if $> -l[0,$>]
  -r[0] [1] -inpaint[1] [0]
  -repeat $1
    --diffusiontensors[1] 0,1,$4,$5,0 -*[2] [0] -smooth[1] [2],$2,$3,0 -rm[2]
  -done
  -endl -endif -done -v +

#@gmic kuwahara : size>0
#@gmic : Apply Kuwahara filter of specified size on selected images.
#@gmic : $ image.jpg --kuwahara 5
kuwahara : -check $1>0
  -e[^-1] "Apply Kuwahara filter of size $1 on image$?."
  -v - -repeat @#
    s={s}
    --dilate[0] $1 -compose_channels[-1] min
    --erode[0] $1 -compose_channels[-1] max
    --[-2,-1]
    $1,1,1,1,{1/$1} -convolve[0] [-1] -transpose[-1] -convolve[0] [-1] -rm[-1]
    p={int($1/2)}
    -a[-2,-1] c
    -f "v1=i(x-"$p",y-"$p",0,"$s",0,1); \
        v2=i(x+"$p",y-"$p",0,"$s",0,1); \
        v3=i(x-"$p",y+"$p",0,"$s",0,1); \
        v4=i(x+"$p",y+"$p",0,"$s",0,1); \
        vm=min(v1,v2,v3,v4); \
        if(c>="$s",i, \
          if(vm==v1,i(x-"$p",y-"$p",0,c,0,1),
            if(vm==v2,i(x+"$p",y-"$p",0,c,0,1),
              if(vm==v3,i(x-"$p",y+"$p",0,c,0,1),
                i(x+"$p",y+"$p",0,c,0,1)))))"
    -channels[-1] 0,{s-2}
  -mv[-1] 0 -done -v +

#@gmic laplacian
#@gmic : Compute Laplacian of selected images.
#@gmic : $ image.jpg -laplacian
laplacian :
  -e[^-1] "Compute Laplacian of image $?."
  -v - -repeat @#
    -if {d==1} -hessian[-1] xxyy -+[-2,-1]
    -else -hessian[-1] xxyyzz -+[-3--1]
    -endif
  -mv[-1] 0 -done -v +

#@gmic lic : _amplitude>0,_channels>0
#@gmic : Generate LIC representation of vector field.
#@gmic : Default values : 'amplitude=30' and 'channels=1'.
#@gmic : $ 400,400,1,2,'if(c==0,x-w/2,y-h/2)' --lic 200,3 -quiver[-2] [-2],10,-13,1,1,255
lic : -skip ${1=30},${2=1}
  -e[^-1] "Generate LIC representation of 2d vector field$?, with amplitude $1 and $2 channel(s)."
  -v - -repeat @#
     -channels[-1] 0,1 -/[-1] {max(abs(@{-1,m}),abs(@{-1,M}))} -vector2tensor[-1]
     100%,100%,100%,$2 -rand[-1] 0,255 -smooth[-1] [-2],$1 -rm[-2]
     -equalize[-1] 256
  -mv[-1] 0 -done -v +

#@gmic map_tones : _threshold>=0,_gamma>=0,_smoothness>=0,nb_iter>=0
#@gmic : Apply tone mapping operator on selected images, based on Poisson equation.
#@gmic : Default values : 'threshold=0.1', 'gamma=0.8', 'smoothness=0.5' and 'nb_iter=30'.
#@gmic : $ image.jpg --map_tones ,
map_tones : -skip ${1=0.1},${2=0.8},${3=0.5},${4=30}
  -e[^-1] "Apply tone mapping operator on image$?, with threshold $1, gamma $2, smoothness $3 and $4 iterations."
  -v - -repeat @#

    # Estimate target divergence for each channel.
    --l[-1] -s[-1] c -repeat @#
      -g[-1] xy,1 -a[-2,-1] c --norm[-1] -orientation[-2]
      m={im} M={iM} -b[-1] $3 -n[-1] $m,$M
      -*[-1] 'alpha=$1*iM;(alpha/(1e-10+i))*(i/(1e-10+alpha))^$2'
     -*[-2,-1] -s[-1] c -g[-2] x,-1 -g[-1] y,-1 -+[-2,-1]
    -mv[-1] 0 -done -a c -endl

    # Start PDE iterations
    -*[-1] 0.25
    -repeat $4
      --laplacian[-2] -*[-1] 0.25 -+[-1] [-3] --[-1] [-2] -*[-1] 800 -+[-3,-1] -/[-2] 801 -c[-2] 0,255
    -done -rm[-1]
  -mv[-1] 0 -done  -v +

#@gmic map_tones_fast : _radius[%]>=0,_power>=0
#@gmic : Apply fast tone mapping operator on selected images.
#@gmic : Default values : 'radius=3%' and 'power=0.3'.
#@gmic : $ image.jpg --map_tones_fast ,
map_tones_fast : -check "${1=3%}>=0 && ${2=0.3}>=0"
  -e[^-1] "Apply fast tone mapping operator on image$?, with radius $1 and power $2."
  -v - -repeat @#
    --luminance[-1] -b[-1] $1 -n[-2,-1] 0,1
    --*[-1] 2 --[-1] 1 -abs[-1] -*[-1] {$2*log(10)} -exp[-1]
    -le[-2] 0.5 -r[-1] [-3]
    --*[-3] -1 -+[-1] 1 -^[-1] [-2] -*[-1] -1 -+[-1] 1 -*[-1] [-3]
    -^[-4,-2] -eq[-2] 0 -*[-3,-2] -+[-2,-1]
  -mv[-1] 0 -done -n 0,255 -v +

#@gmic meancurvature_flow : _nb_iter>=0,_dt,_sequence_flag={ 0 | 1 }
#@gmic : Apply iterations of the mean curvature flow on selected images.
#@gmic : Default values : 'nb_iter=10', 'dt=30' and 'keep_sequence=0'.
#@gmic : $ image.jpg --meancurvature_flow 20
meancurvature_flow : -skip ${1=10},${2=30},${3=0}
  -e[^-1] "Apply $1 iterations of the mean curvature flow on image$?, with time step $2."
  -v - -pde_flow $1,$2,iee,$3 -v +

#@gmic normalize_local : _amplitude>=0,_radius>0,_n_smooth>=0[%],_a_smooth>=0[%],_is_cut={ 0 | 1 },_min=0,_max=255
#@gmic : Normalize selected images locally.
#@gmic : Default values : 'amplitude=3', 'radius=16', 'n_smooth=4%', 'a_smooth=2%', 'is_cut=1', 'min=0' and 'max=255'.
#@gmic : $ image.jpg --normalize_local 8,10
normalize_local :
  -check "${1=3}>=0 && ${2=16}>0 && isbool(${5=1})" -skip ${3=4%},${4=2%},${6=0},${7=255}
  -e[^-1] "Normalize image$? locally, with amplitude $1, radius $2, neighborhood smoothness $3 and average smoothness $4."
  -v - -repeat @#
    --l[-1] -erode {2*$2+1} -s c -min -endl
    --l[-2] -dilate {2*$2+1} -s c -max -endl
    --b[-3] $4 -b[-3,-2] $3
    ---[-2] [-3] -+[-1] 0.01 --[-5] [-4] -/[-5,-1]
    -*[-3,-2] {$1+1} -*[-1] -$1 -+[-3] [-1] -+[-2,-1]
    -if $5 -max[-2] $6 -min[-1] $7 -endif
    --[-1] [-2] -*[-3,-1] -+[-2,-1]
    -if $5 -c[-1] $6,$7 -endif
  -mv[-1] 0 -done -v +

#@gmic normalized_cross_correlation
#@gmic : Compute normalized cross-correlation using two-by-two selected images.
#@gmic : $ image.jpg --shift -30,-20 -normalized_cross_correlation
normalized_cross_correlation :
  -e[^-1] "Compute normalized cross-correlation using two-by-two image$?."
  -v - -repeat {int(@#/2)}
    -norm[-2,-1] -fft[-2] -fft[-1] [-2,-1] -mul[-2] [-5] -mul[-1] [-6]
    --[-2,-1] -*[-5,-3] -*[-3,-2] -+[-3,-2] [-2,-1] -a[-2,-1] c -norm[-1]
    -/[-3] [-1] -/[-2,-1] -ifft[-2,-1] -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic phase_correlation
#@gmic : Estimate translation vector using two-by-two selected images.
#@gmic : $ image.jpg --shift -30,-20 --phase_correlation -unroll[-1] y
phase_correlation :
  -e[^-1] "Estimate translation vector using two-by-two image$?."
  -v - -repeat {int(@#/2)}
    -normalized_cross_correlation[-2,-1]
    (@{-1,C}) -*[-1] 2 -s[-1] x -rm[-1]
    -if {@-3>@{-4,w}} --[-3] @{-4,w} --[-3] @{-4,w} -endif
    -if {@-2>@{-4,h}} --[-2] @{-4,h} --[-2] @{-4,h} -endif
    -if {@-1>@{-4,d}} --[-1] @{-4,d} --[-1] @{-4,d} -endif
    -a[-3--1] c -/[-1] 2 -*[-1] -1 -rm[-2]
  -mv[-1] 0 -done -v +

#@gmic pde_flow : _nb_iter>=0,_dt,_velocity_command,_keep_sequence={ 0 | 1 }
#@gmic : Apply iterations of a generic PDE flow on selected images.
#@gmic : Default values : 'nb_iter=10', 'dt=30', 'velocity_command=laplacian' and 'keep_sequence=0'.
#@gmic : $ image.jpg --pde_flow 20
pde_flow : -skip ${1=10},${2=30},${3=laplacian},${4=0}
  -e[^-1] "Apply $1 iterations of the velocity flow '$3' on image$?, with time step $2."
  -v - -repeat @# -l[-1] -repeat $1
    --$3[-1] -*[-1] {$2/(0.01+max(abs(im),abs(iM)))}
    -if $4 -+[-1] [-2] -else -+[-2,-1] -endif
  -done -if $4 -rm[0] -endif -a x -endl
  -mv[-1] 0 -done -if $4 -s x,$1 -endif -v +

#@gmic red_eye : 0<=_threshold<=100,_smoothness>=0,0<=attenuation<=1
#@gmic : Attenuate red-eye effect in selected images.
#@gmic : Default values : 'threshold=75', 'smoothness=3.5' and 'attenuation=0.1'.
#@gmic : $ image.jpg --red_eye ,
red_eye : -skip ${1=75},${2=3.5},${3=0.1}
  -e[^-1] "Attenuate red-eye effect in image$?, with threshold $1, smoothness $2 and attenuation $3."
  -v - -to_rgb -rgb2ycbcr -repeat @#
    -s[-1] c --[-1] 128 --t[-1] $1% -b[-1] $2 -sqrt[-1] -*[-1] -1 -+[-1] 1
    -n[-1] $3,1 -*[-2,-1] -+[-1] 128 -a[-3--1] c -ycbcr2rgb[-1]
  -mv[-1] 0 -done -v +

#@gmic remove_hotpixels : _mask_size>0, _threshold[%]>0
#@gmic : Remove hot pixels in selected images.
#@gmic : Default values : 'mask_size=3' and 'threshold=10%'.
#@gmic : $ image.jpg -noise 10,2 --remove_hotpixels ,
remove_hotpixels : -check ${1=3}>0 -skip ${2=10%}
  -e[^-1] "Remove hot pixels in image$?, with mask size $1 and threshold $2."
  -v - -repeat @#
    --median[-1] $1 ---[-1,-2] -abs[-1] -t[-1] $2
    -*[-2] [-1] -==[-1] 0 -*[-3,-1] -+[-2,-1]
  -mv[-1] 0 -done -v +

#@gmic remove_pixels : density>=0,_pixel_sum>=0
#@gmic : Remove (i.e. set to 0) specified density (in percent) of non-zero pixels to 0.
#@gmic : Specified density is regarded against 'pixel_sum' except if it is set to '0'
#@gmic : (in this case, 'pixel_sum' has default value 'width*height').
#@gmic : Default value : 'density=10', 'base_density=0'.
#@gmic : $ image.jpg --remove_pixels 50
remove_pixels : -check "${1=10}>=0 && ${2=0}>=0"
  -e[^-1] "Remove $1% of non-zero pixels of image$?."
  -v - -repeat @# -l[$>]
    --norm[-1] -gt[-1] 0
    -if $2 rate={$1*$2/max(1e-8,@{-1,+})}
    -else rate={$1*w*h/max(1e-8,@{-1,+})}
    -endif
    -rm[-1]
    100%,100% -rand[-1] 0,1 -t[-1] $rate% -*[-2,-1]
  -endl -done -v +

#@gmic richardson_lucy : amplitude[%]>=0,_nb_iter>=0,_dt>=0,_regul>=0,_regul_type={ 0=Tikhonov | 1=meancurv. | 2=TV }
#@gmic : Deconvolve image with the iterative Richardson-Lucy algorithm.
#@gmic : Default values : 'nb_iter=10', 'dt=20', 'regul=0.7' and 'regul_type=1'.
#@gmic : $ image.jpg -blur 3 --richardson_lucy 3,40,20,0.01
richardson_lucy : -check "${2=10}>=0 && ${3=20}>=0 && ${4=0.7}>=0" -skip ${5=1}
  -e[^-1] "Deconvolve image$? with the Richardson-Lucy algorithm, with sigma $1, $2 iterations, time step $3 and regularization $4."
  -v - -repeat @#
    [-1]
    -repeat $2
      -if {$5>=2} --curvature[-1]                         # TV regularization.
      -elif {$5>=1} --iee[-1]                             # Meancurv. regularization.
      -else --laplacian[-1]                               # Tikhonov regularization.
      -endif
      -*[-1] $4
      --b[-2] $1 --[-1] [-4]                              # Data fidelity term.
      --[-2,-1]
      -*[-1] {$3/(0.0001+max(abs(@{-1,m}),abs(@{-1,M})))} # Adaptive time step.
      -+[-2,-1]                                           # Update image.
    -done
    -rm[-2]
  -mv[-1] 0 -done -v +

#@gmic solidify
#@gmic : Replace transparent regions of a RGBA image by morphologically interpolated color.
#@gmic : $ image.jpg --luminance -ge[-1] 120 -*[-1] 255 -append c --solidify -display_rgba
solidify :
  -e[^-1] "Replace transparent regions of RGBA image$? by morphologically interpolated colors."
  -v - -repeat @# -l[$>] -to_a
    [-1] -split_opacity[-2] -t[-2] 50% -*[-1] [-2]
    -replace_color[-1] 0,0,0,0,0,0,-1,-1,-1,-1 -to_rgb[-1]
    -do
      --dilate[-1] 3
      -replace_color[-2] 0,0,-1,-1,-1,1000,1000,1000
      -erode[-2] 3
      -replace_color[-2] 0,0,1000,1000,1000,-1,-1,-1
      -+[-2,-1] -/[-1] 2
      -j[-1] [-3],0,0,0,0,1,[-2]
    -while {im<0}
    -rm[-3,-2]
  -endl -done -v +

#@gmic solidify_linear : _sigma>=1,_dsigma>=1,0<=_precision<=1
#@gmic : Replace transparent regions of a RGBA image by linearly interpolated color.
#@gmic : Default values : 'sigma=1.5', 'dsigma=1' and 'precision=0.5'.
#@gmic : $ image.jpg --luminance -ge[-1] 120 -*[-1] 255 -append c --solidify_linear , -display_rgba
solidify_linear : -check "${1=1.5}>=1 && ${2=1}>=1 && ${3=0.5}>=0 && $3<=1"
  -e[^-1] "Replace transparent regions of RGBA image$? by linearly interpolated colors, with sigma $1, dsigma $2 and precision $3."
  -v - -repeat @# -l[$>]
    -split_opacity
    -if {@#>1}
      -t[-1] 50% -*[-2] [-1]
      sigma=$1 -do
        N={v=round(3*$sigma);min(33,max(3,v+1-(v%2)))}
        $N,$N -=[-1] 1,50%,50% -distance[-1] 1 -*[-1] {-1/$sigma^2} -exp[-1] -normalize_sum[-1]
        --convolve[-3,-2] [-1] -rm[-3]
        -max[-1] 1e-5 -/[-2,-1]
        --dilate[-2] {v=round((1/3-$N/6)*$3+$N/2);max(3,v+1-(v%2))}
        --[-3] [-1] -*[-2] [-3] -rm[-3]
        --[-3,-2]
        sigma={$sigma*$2}
      -while {!im}
     -rm[-1]
   -endif
 -endl -done -v +

#@gmic split_freq : smoothness>0[%]
#@gmic : Split selected images into low and high frequency parts.
#@gmic : $ image.jpg -split_freq 2%
split_freq :
  -e[^-1] "Split image$? into low and high frequency parts, with smoothness $1."
  -v - -repeat @#
    --b[-1] $1 --[-2] [-1] -rv[-2,-1]
  -mv[-2,-1] 0 -done -v +

#@gmic tv_flow : _nb_iter>=0,_dt,_sequence_flag={ 0 | 1 }
#@gmic : Apply iterations of the total variation flow on selected images.
#@gmic : Default values : 'nb_iter=10', 'dt=30' and 'keep_sequence=0'.
#@gmic : $ image.jpg --tv_flow 40
tv_flow : -skip ${1=10},${2=30},${3=0}
  -e[^-1] "Apply $1 iterations of the total variation flow on image$?, with time step $2."
  -v - -pde_flow $1,$2,curvature,$3 -v +

#@gmic unsharp : radius[%]>=0,_amount>=0,_threshold[%]>=0
#@gmic : Apply unsharp mask on selected images.
#@gmic : Default values : 'amount=2' and 'threshold=0'.
#@gmic : $ image.jpg -blur 3 --unsharp 1.5,15 -cut 0,255
unsharp : -check "${2=2}>=0" -skip ${3=0}
  -e[^-1] "Apply unsharp mask on image$?, with radius $1, amount $2 and threshold $3."
  -v - -repeat @#
    --b[-1] $1 --[-1] [-2]
    -if $3 --norm[-1] -t[-1] $3 -*[-2,-1] -endif
    -*[-1] $2 --[-2,-1]
  -mv[-1] 0 -done -v +

#@gmic unsharp_octave : _nb_scales>0,_radius[%]>=0,_amount>=0,threshold[%]>=0
#@gmic : Apply octave sharpening on selected images.
#@gmic : Default values : 'nb_scales=4', 'radius=1', 'amount=2' and 'threshold=0'.
#@gmic : $ image.jpg -blur 3 --unsharp_octave 4,5,15 -cut 0,255
unsharp_octave : -check "${1=4}>0 && ${3=2}>=0" -skip ${2=1},${4=0}
  -e[^-1] "Apply octave sharpening on image$?, with $1 scales, radius $2, amount $3 and threshold $4."
  -v - -repeat @#
    -l[-1] --f 0 weight=0 -repeat $1
      --unsharp[0] {$2*2^-@{<,-1}},$3,$4 -*[-1] {2^-$>} weight={$weight+2^-$>} -+[1,-1]
    -done -rm[0] -/[-1] $weight -endl
  -mv[-1] 0 -done -v +

#@gmic watermark_fourier : text,_size>0
#@gmic : Add an textual watermark in the frequency domain of selected images.
#@gmic : Default value : 'size=32'.
#@gmic : $ image.jpg --watermark_fourier "Watermarked !" --display_fft -remove[-3,-1] -normalize 0,255 -append[-4,-2] y -append[-2,-1] y
watermark_fourier : -check ${2=32}>0
  -e[^-1] "Add textual watermark '$1' with size $2 in the frequency domain of image$?."
  -v - -i[0] 1 -text[0] "$1",0,0,$2,1,1 -t[0] 0.5 -autocrop[0] 0
  -repeat {@#-1} w2={int(w/2)} h2={int(h/2)}
    -fft[-1]
    -shift[-2,-1] $w2,$h2,0,0,2
    [0],[0],1,{s}
    -j[-3,-2] [-1],3,3,0,0,1,[0]
    -mirror[0] x
    -j[-3,-2] [-1],{@{-2,w}-2-@{0,w}},3,0,0,1,[0]
    -mirror[0] y
    -j[-3,-2] [-1],{@{-2,w}-2-@{0,w}},{@{-2,h}-2-@{0,h}},0,0,1,[0]
    -mirror[0] x
    -j[-3,-2] [-1],3,{@{-2,h}-2-@{0,h}},0,0,1,[0]
    -mirror[0] y
    -rm[-1]
    -shift[-2,-1] -$w2,-$h2,0,0,2
    -ifft[-2,-1] -rm[-1]
  -mv[-1] 1 -done
  -rm[0] -v +

#---------------------------------
#
#@gmic :: Features extraction
#
#---------------------------------

#@gmic area : tolerance>=0,is_high_connectivity={ 0 | 1 }
#@gmic : Compute area of connected components in selected images.
#@gmic : Default values : 'is_high_connectivity=0'.
#@gmic : $ image.jpg -luminance -stencil[-1] 1 --area 0
area : -check "$1>=0" -skip ${2=0}
  -e[^-1] "Compute area of connected components in image$?, with tolerance $1 and "@{"-if $2 -u high -else -u low -endif"}" connectivity."
  -v - -repeat @# -l[$>] -s c
    -repeat @# -label[-1] $1,$2 nb={1+iM} --histogram[-1] $nb,0,{$nb-1} -map[-2] [-1] -rm[-1] -mv[-1] 0 -done
  -a c -endl -done -v +

#@gmic area_fg : tolerance>=0,is_high_connectivity={ 0 | 1 }
#@gmic : Compute area of connected components for non-zero values in selected images.
#@gmic : Similar to '-area' except that 0-valued pixels are not considered.
#@gmic : Default values : 'is_high_connectivity=0'.
#@gmic : $ image.jpg -luminance -stencil[-1] 1 --area_fg 0
area_fg : -check "$1>=0" -skip ${2=0}
  -e[^-1] "Compute area of foreground connected components in image$?, with tolerance $1 and "@{"-if $2 -u high -else -u low -endif"}" connectivity."
  -v - -repeat @# -l[$>] -s c
    -repeat @# -label_fg[-1] $1,$2 nb={1+iM} --histogram[-1] $nb,0,{$nb-1} -=[-1] 0 -map[-2] [-1] -rm[-1] -mv[-1] 0 -done
  -a c -endl -done -v +

#@gmic float2fft8
#@gmic : Convert selected float-valued images to 8bits fourier representations.
float2fft8 :
  -e[^-1] "Convert float-valued image$? to 8bits fourier representations."
  -v - -repeat @#
    -fftpolar[-1] -+[-2] 1 -log[-2] -float2int8[-2,-1] -a[-2,-1] y
  -mv[-1] 0 -done -v +

#@gmic fft82float
#@gmic : Convert selected 8bits fourier representations to float-valued images.
fft82float :
  -e[^-1] "Convert float-valued image$? to 8bits fourier representations."
  -v - -repeat @#
    -s[-1] y,2 -int82float[-2,-1] -exp[-2] --[-2] 1 -ifftpolar[-2,-1]
  -mv[-1] 0 -done -v +

#@gmic fftpolar
#@gmic : Compute fourier transform of selected images, as centered magnitude/phase images.
#@gmic : $ image.jpg -fftpolar -ellipse 50%,50%,10,10,0,1,0 -ifftpolar
fftpolar :
  -e[^-1] "Compute fourier transform of image$?, as centered magnitude/phase images."
  -v - -repeat @# w2={int(w/2)} h2={int(h/2)} d2={int(d/2)}
    -fft[-1] -complex2polar[-2,-1]
    -shift[-2,-1] -$w2,-$h2,-$d2,0,2
  -mv[-2,-1] 0 -done -v +

#@gmic histogram_cumul : _nb_levels>0,_is_normalized={ 0 | 1 },_val0[%],_val1[%]
#@gmic : Compute cumulative histogram of selected images.
#@gmic : Default values : 'nb_levels=256', 'is_normalized=0' and 'val0=val1=0'.
#@gmic : $ image.jpg --histogram_cumul 256 -histogram[0] 256 -display_graph 400,300,3
histogram_cumul : -check ${1=256}>0 -skip ${2=0} -skip ${3=0},${4=0}
  -if $2 -e[^-1] "Compute normalized cumulative histogram of image$?, using $1 levels."
  -else -e[^-1] "Compute cumulative histogram of image$?, using $1 levels." -endif
  -v - -histogram $1,$3,$4 -cumul -if $2 -repeat @# -/[$>] @{$>,M} -done -endif -v +

#@gmic hough : _width>0,_height>0,gradient_norm_voting={ 0 | 1 }
#@gmic : Compute hough transform (theta,rho) of selected images.
#@gmic : Default values : 'width=512', 'height=width' and 'gradient_norm_voting=1'.
#@gmic : $ image.jpg --blur[-1] 1.5 -hough[-1] 400,400 -blur[-1] 0.5 -+[-1] 1 -log[-1]
hough : -check "${1=512}>0 && ${2=$1}>0" -skip ${3=1}
  -e[^-1] "Compute $1x$2 hough transform of image$?, "@{"-if $3 -u with -else -u without -endif"}" gradient norm voting."
  -v - -slices 50% -luminance -repeat @#
    rhomax={sqrt(w^2+h^2)/2}
    -g[-1]
    (0,{w-1}) (0;{@{-2,h}-1}) -r[-2,-1] @{-3,w},@{-3,h},1,1,3 --[-2] {w/2} --[-1] {h/2}
    -complex2polar[-4--1] --[-1] [-3] -polar2complex[-2,-1] -rm[-1]
    --lt[-1] 0 -*[-1] {pi} -+[-3,-1] -abs[-1] -%[-2] {2*pi}
    -*[-1] {$2/$rhomax} -*[-2] {0.5*$1/pi}
    -y[-3--1] x {w} -mv[-4] @# -if {!$3} -f[-1] 1 -endif -a[-4--1] y
    -pointcloud[-1] 1 -r[-1] $1,$2,1,1,0
  -mv[-1] 0 -done -v +

#@gmic ifftpolar
#@gmic : Compute inverse fourier transform of selected images, from centered magnitude/phase images.
ifftpolar :
  -e[^-1] "Compute inverse fourier transform of image$?, from centered magnitude/phase images."
  -v - -repeat {int(@#/2)} w2={int(w/2)} h2={int(h/2)} d2={int(d/2)}
    -shift[-2,-1] $w2,$h2,$d2,0,2
    -polar2complex[-2,-1] -ifft[-2,-1] -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic isophotes : _nb_levels>0
#@gmic : Render isophotes of selected images on a transparent background.
#@gmic : Default value : 'nb_levels=64'
#@gmic : $ image.jpg -blur 2 -isophotes 6 -dilate_circ 5 -display_rgba
isophotes : -skip ${1=64}
  -e[^-1] "Render isophote maps from images$?, with $1 levels."
  -v - -to_rgba -repeat @# -l[-1]
    --luminance -repeat $1 --isoline3d[1] {$>*255/($1-1)} -done -rm[1] -+3d[1--1] -col3d[-1] 1,1,1
    [0],[0] mode=@* -m3d 0 -object3d[-1] [-2],0,0 -m3d $mode -rm[-2] -*[-2,-1]
  -endl -mv[-1] 0 -done -v +

#@gmic label_fg : tolerance>=0,is_high_connectivity={ 0 | 1 }
#@gmic : Label connected components for non-zero values (foreground) in selected images.
#@gmic : Similar to '-label' except that 0-valued pixels are not labeled.
#@gmic : Default value : 'is_high_connectivity=0'.
label_fg : -check "$1>=0" -skip ${2=0}
  -e[^-1] "Label foreground connected components on image [1], with tolerance $1 and "@{"-if $2 -u high -else -u low -endif"}" connectivity."
  -v - -repeat @#
    -if {d>1} --z[-1] -1,-1,-1,{w-1},{h-1},{d-1} -label[-1] $1,$2 -z[-1] 1,1,1,{w-1},{h-1},{d-1}
    -else --z[-1] -1,-1,{w-1},{h-1} -label[-1] $1,$2 -z[-1] 1,1,{w-1},{h-1}
    -endif
    -neq[-2] 0 -*[-2,-1]
    --histogram[-1] {1+iM} -neq[-1] 0 -*[-1] 'x' -lines[-1] -1,0 -label[-1] 0 -lines[-1] 1,1
    -map[-2] [-1] -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic max_patch : _patch_size>=1
#@gmic : Return locations of maximal values in local patch-based neighborhood of given size for selected images.
#@gmic : Default value : 'patch_size=16'.
#@gmic : $ image.jpg -norm --max_patch 16
max_patch : -check "isint(${1=16}) && $1>=1"
  -e[^-1] "Return locations of maximal values in local patch neighborhood of size $1, in image$?."
  -v - -repeat @#
    --dilate[-1] $1 -==[-2,-1]
  -mv[-1] 0 -done -v +

#@gmic min_patch : _patch_size>=1
#@gmic : Return locations of minimal values in local patch-based neighborhood of given size for selected images.
#@gmic : Default value : 'patch_size=16'.
#@gmic : $ image.jpg -norm --min_patch 16
min_patch : -check "isint(${1=16}) && $1>=1"
  -e[^-1] "Return locations of minimal values in local patch neighborhood of size $1, in image$?."
  -v - -repeat @#
    --erode[-1] $1 -==[-2,-1] -mv[-1] 0
  -done -v +

#@gmic minimal_path : x0[%]>=0,y0[%]>=0,z0[%]>=0,x1[%]>=0,y1[%]>=0,z1[%]>=0
#@gmic : Compute minimal path between two points on selected potential maps.
#@gmic : $ image.jpg --gradient_norm -f[-1] 1/(1+i) -minimal_path[-1] 0,0,0,100%,100%,0 -pointcloud[-1] 0 -*[-1] 280 -to_rgb[-1] -resize[-1] [-2],0 -or
minimal_path : -check "$1>=0 && $2>=0 && $3>=0"
  -e[^-1] "Compute minimal path between points ($1,$2,$3) and ($4,$5,$6) for potential map$?."
  -v - -repeat @# -l[$>]
    -distance ${4-6}
    x={round(if(@{"-is_percent $1"},$1*(w-1),$1))}
    y={round(if(@{"-is_percent $2"},$2*(h-1),$2))}
    z={round(if(@{"-is_percent $3"},$3*(d-1),$3))}
    ($x;$y;$z)
    -do
      p=@{0,($x,$y,$z,1)}
      -if {$p==1}   x={$x-1}
      -elif {$p==2} x={$x+1}
      -elif {$p==3} y={$y-1}
      -elif {$p==4} y={$y+1}
      -elif {$p==5} z={$z-1}
      -elif {$p==6} z={$z+1}
      -endif
      ($x;$y;$z)
    -while $p
    -rm[0,-1] -a x
  -endl -mv[-1] 0 -done -v +

#@gmic plot2value
#@gmic : Retrieve values from selected 2d graph plots.
#@gmic : $ 400,300,1,1,'if(y>300*abs(cos(x/10+2*?)),1,0)' --plot2value --display_graph[-1] 400,300
plot2value :
  -e[^-1] "Retrieve values from 2d graph plot$?."
  -v - -repeat @# -l[$>]
    -s c -t 50%
    -repeat @# (1,{w}) -r[-1] [-2],3 -*[-2,-1] -histogram[-1] {w},1,{w} -mv[-1] 0 -done
    -a c
  -endl -done -v +

#@gmic pointcloud : _type = { -X=-X-opacity | 0=binary | 1=cumulative | 2=label }
#@gmic : Convert a Nx1, Nx2, Nx3 or NxM image as a point cloud in a 1d/2d or 3d binary image.
#@gmic : If 'M'>3, the 3-to-M lines sets the (M-3)-dimensional color at each point.
#@gmic : Default value : 'type=0'.
#@gmic : $ 3000,2 -rand 0,400 --pointcloud 0
#@gmic : $ 3000,2 -rand 0,400 {w} {w},3 -rand[-1] 0,255 -append y --pointcloud 0
pointcloud : -skip ${1=0}
  -e[^-1] "Convert image$? to point clouds, in "\
          @{"-if {$1<0} -u \""{-$1}"-opacity\" -elif {$1==0} -u \"binary\" -elif {$1==1} -u \"cumulative\" -else -u \"labeling\" -endif"}\
          " mode."
  -v - -repeat @#
    -if {"d>1 || s>1"} -error "Invalid input image "{w}x{h}x{d}x{s}". Should be NxMx1x1." -endif

    # Retrieve coordinates and color infos.
    -lines[-1] 0,{max(2,h-1)}
    -sh[-1] 0,0,0,0 -round[-1] dx={iM+1}
    -sh[-2] 1,1,0,0 -round[-1] dy={iM+1}
    -sh[-3] 2,2,0,0 -round[-1] dz={iM+1}
    -*[-1] $dy -+[-2] [-1] -f[-1] 0 -rm[-3--1]

    # Create corresponding 3d object (manage large point clouds).
    -l[-1]
      -s x,-1000000
      -repeat @#
        nbp={w}
        -if {h>3} --lines[-1] 3,100% -lines[-2] 0,2 -else 100%,1,1,1,1 -if {$1==2} -f[-1] 1+x -endif -endif
        spectrum={h} -i[-2] (-128;1;1;{h}) -r[-2] {w} -a[-2,-1] y
        -i[-3] ({'CImg3d'}) -transpose[-3--1] -i[-3] ($nbp;$nbp) # Header
        -i[-2] 1,$nbp,1,1,1 -i[-2] 1,$nbp,1,1,y -a[-3,-2] x      # Vertices and primitives.
        1,$nbp,1,1,{if($1<0,-$1,if($1==1,-1,1))}                 # Opacities.
        -y[-4--2] y -a[-6--1] y                                  # Merge object attributes.
      -mv[-1] 0 -done
      -+3d
    -endl

    # Draw corresponding point cloud.
    $dx,{$dy*$dz},1,$spectrum mode=@* -m3d 0 -object3d[-1] [-2],0,0,0,1,0 -m3d $mode -rm[-2] -r[-1] $dx,$dy,$dz,100%,-1
  -mv[-1] 0 -done -v +

#@gmic segment_watershed : _threshold>=0,_keep_watershed={ 0 | 1 }
#@gmic : Apply watershed segmentation on selected images.
#@gmic : Default values : 'threshold=2' and 'keep_watershed=1'.
#@gmic : $ image.jpg --segment_watershed 2,0
segment_watershed : -check "${1=2}>=0" -skip ${2=1}
  -e[^-1] "Apply watershed segmentation on image$?, with edge threshold $1."
  -v - -repeat @#
    -+[-1] {1+@{-1,m}}
    --gradient_norm[-1]
    -if {d>1} --f[-1] "if(i<$1 && i<i(x+1) && i<i(x-1) && i<i(x,y+1) && i<i(x,y-1) && i<i(x,y,z+1) && i<i(x,y,z-1),1,0)"
    -else --f[-1] "if(i<$1 && i<i(x+1) && i<i(x-1) && i<i(x,y+1) && i<i(x,y-1),1,0)"
    -endif
    -*[-3,-1] -*[-1] -1 -watershed[-2] [-1],$2 -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic skeleton : _smoothness[%]>=0
#@gmic : Compute skeleton of binary shapes using distance transform.
#@gmic : Default value : 'smoothness=0'.
#@gmic : $ image.jpg -threshold 50% --skeleton 0
skeleton : -check ${1=0}>=0
  -e[^-1] "Compute skeleton of binary image$?."
  -v - -t 50% -distance 0 -b $1 -sharpen 1e10 -t 100%
  -repeat @# --erode[-1] 2 --[-2,-1] -done -v +

#@gmic thinning
#@gmic : Compute skeleton of binary shapes using morphological thinning
#@gmic : (This is a quite slow iterative proces)
#@gmic : $ image.jpg -threshold 50% --thinning
thinning :
  -e[^-1] "Compute skeleton of binary image$?, using morphological thinning."
  -v - -t 50% -* 2 -- 1
  (-1,-1,-1;0,1,0;1,1,1) (0,-1,-1;1,1,-1;0,1,0) --rotate[-2,-1] 90 --rotate[-2,-1] 90 --rotate[-2,-1] 90
  -repeat @#  # Start skeleton refinement.
    bavg=@{-9,+}
    -repeat 99999
      --correlate[-9] [-8] -t[-1] 7 -*[-1] 2 --[-10,-1]
      --correlate[-9] [-7] -t[-1] 6 -*[-1] 2 --[-10,-1]
      --correlate[-9] [-6] -t[-1] 7 -*[-1] 2 --[-10,-1]
      --correlate[-9] [-5] -t[-1] 6 -*[-1] 2 --[-10,-1]
      --correlate[-9] [-4] -t[-1] 7 -*[-1] 2 --[-10,-1]
      --correlate[-9] [-3] -t[-1] 6 -*[-1] 2 --[-10,-1]
      --correlate[-9] [-2] -t[-1] 7 -*[-1] 2 --[-10,-1]
      --correlate[-9] [-1] -t[-1] 6 -*[-1] 2 --[-10,-1]
      aavg=@{-9,+} -if {$aavg==$bavg} -break -endif bavg=$aavg
    -done
  -mv[-9] 0 -done -rm[-8--1] -+ 1 -/ 2 -v +

#@gmic tones : N>0
#@gmic : Get N tones masks from selected images.
#@gmic : $ image.jpg --tones 3
tones : -check $1>0
  -e[^-1] "Get $1 tones masks from image$?."
  -v - -norm -n 0,100000 -round 1 -repeat @#
    t0=0 -repeat {$1-1} t1={round(($>+1)*100000/$1-1)} --t2[{-1-$>}] $t0,$t1 t0={$t1+1} -done
    -t2[-$1] $t0,100% -mv[-$1] @#
  -mv[-$1--1] 0 -done -v +

#@gmic topographic_map : _nb_levels>0,_smoothness
#@gmic : Render selected images as topographic maps.
#@gmic : Default values : 'nb_levels=16' and 'smoothness=2'.
#@gmic : $ image.jpg --topographic_map 10
topographic_map : -skip ${1=16},${2=2}
  -e[^-1] "Render topographic maps from image$?, with $1 levels and smoothness $2."
  -v - -to_rgb -repeat @#
    --b[-1] $2 -isophotes[-1] $1 -t[-1] 0.1 -to_rgb[-1] --norm[-1]
    -line[-2,-1] 100%,0,100%,100%,1,1 -line[-2,-1] 0,100%,100%,100%,1,1
    -line[-2,-1] 0,0,100%,0,1,1 -line[-2,-1] 0,0,0,100%,1,1
    -_topographic_map0[-3--1]
    -_topographic_map[-3--1]
    -rm[-3,-1]
  -mv[-1] 0 -done -v +

_topographic_map0 :
  -repeat 4000
    xy={?(w)},{?(h)}
    -if {@{-1,($xy)}==0}
      -flood[-2] $xy,0,0,0,1,@{-3,($xy,0,0)},@{-3,($xy,0,1)},@{-3,($xy,0,2)}
      -flood[-1] $xy,0,0,0,1,1
    -endif
  -done

_topographic_map :
  -do
    (@{-1,c}) xy=@{-1,0},@{-1,1} -rm[-1]
    -if {@{-1,($xy)}==0}
      -flood[-2] $xy,0,0,0,1,@{-3,($xy,0,0)},@{-3,($xy,0,1)},@{-3,($xy,0,2)}
      -flood[-1] $xy,0,0,0,1,1
    -else -return
    -endif
  -while 1

#---------------------------------
#
#@gmic :: Image drawing
#
#---------------------------------

#@gmic ball : _R,_G,_B
#@gmic : Draw a colored RGBA ball sprite on selected images.
#@gmic : Default values : 'R=255', 'G=R' and 'B=R'.
#@gmic : $ 32,32 64,64 200,200 256,256 -ball 255,164,100
ball : -skip ${1=255},${2=$1},${3=$2}
  -e[^-1] "Draw ball sprite on image$?, with color ($1,$2,$3)."
  -v - -to_rgba
  -repeat @#
    mwh={min(w,h)}
    -sh[-1] 3,3 -f[-1] 0 -rm[-1]
    -ellipse[-1] {0.5*$mwh},{0.5*$mwh},{0.5*$mwh-4},{0.5*$mwh-4},0,1,$1,$2,$3,1
    -sh[-1] 0,2 -*[-1] '($mwh+y-x)/(2*w)' -rm[-1]
    -ellipse[-1] {$mwh*0.7},{$mwh*0.3},{min(30,$mwh*$mwh/512)},{min(30,$mwh*$mwh/512)},0,{min($mwh/64,1)},255,255,255,1
    -sh[-1] 0,2 -b[-1] {0.02*$mwh} -rm[-1]
    -sh[-1] 3,3 -*[-2] [-1] -dilate[-1] 3 -rm[-1]
    -sh[-1] 0,2 -+[-1] 'if(i&&(!i(x-1)||!i(x+1)||!i(x,y-1)||!i(x,y+1)),if(c==0,$1,if(c==1,$2,$3))/6,0)' -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic chessboard : size1>0,_size2>0,_offset1,_offset2,_angle,_opacity,_color1,..,_color2,..
#@gmic : Draw chessboard on selected images.
#@gmic : Default values : 'size2=size1', 'offset1=offset2=0', 'angle=0', 'opacity=1', 'color1=0' and 'color2=255'.
#@gmic : $ image.jpg -chessboard 32,32,0,0,25,0.3,255,128,0,0,128,255
chessboard : -check "$1>0 && ${2=$1}>0" -skip ${3=0},${4=0},${5=0},${6=1},${7=0},${8=255}
  -e[^-1] "Draw chessboard on image$?, with sizes ($1,$2), offsets ($3,$4), angle $5°, opacity $6 and colors (${7--1})."
  -v - -i[0] (${7--1}) -r[0] {@{0,w}/2},1,1,2,-1 -permute[0] cyzx
  -repeat {@#-1}
    w={w} h={h} theta={$5*pi/180}
    ($3,{$3+$w-1};$3,{$3+$w-1}^$4,$4;{$4+$h-1},{$4+$h-1}) -r[-1] $w,$h,1,2,3
    -r[-1] {$w*$h},2,1,1,-1
    -i[-2] ({cos($theta)},{-sin($theta)};{sin($theta)},{cos($theta)}) -**[-2,-1]
    -r[-1] $w,$h,1,2,-1
    -%[-1] {$1+$2} ->=[-1] $1 -s[-1] c -xor[-2,-1] -map[-1] [0] -r[-1] 100%,100%,1,[-2]
    -j[-2] [-1],0,0,0,0,$6 -rm[-1]
  -mv[-1] 1 -done -rm[0] -v +

#@gmic gaussian : _sigma1[%],_sigma2[%],_angle
#@gmic : Draw a centered gaussian on selected images, with specified standard deviations and orientation.
#@gmic : Default values : 'sigma1=3', 'sigma2=sigma1' and 'angle=0'.
#@gmic : $ 400,400 -gaussian 100,30,45
gaussian : -skip ${1=3},${2=$1},${3=0}
  -e[^-1] "Draw centered gaussian on image$? with standard deviations ($1,$2) and angle $3°."
  -v -
  u={cos($3*pi/180)}
  v={sin($3*pi/180)}
  dmax={max(w,h)}
  -if {isval($1)} l1=$1 -else l1={${1}10000*$dmax/100} -endif
  -if {isval($2)} l2=$2 -else l2={${2}10000*$dmax/100} -endif
  l1={1/(2*max(1/3,$l1)^2)}
  l2={1/(2*max(1/3,$l2)^2)}
  A={$l1*$u*$u+$l2*$v*$v}
  B={($l1-$l2)*$u*$v}
  C={$l1*$v*$v+$l2*$u*$u}
  -repeat @#
    w={w} h={h} d={d} s={s} -rm[-1]
    ({-$w/2},{$w/2}) -r[-1] $w,$h,1,1,3
    -f[-1] "Y=y-"{$h/2};$A"*i*i+2*"$B"*i*Y+"$C*"Y*Y"
    -*[-1] -1 -exp[-1] -r[-1] $w,$h,$d,$s
  -mv[-1] 0 -done -v +

#@gmic marble : _image_weight,_pattern_weight,_angle,_amplitude,_sharpness>=0,_anisotropy>=0,_alpha,_sigma,_cut_low>=0,_cut_high>=0
#@gmic : Generate a marble like pattern.
#@gmic : Default values : 'image_weight=0.2', 'pattern_weight=0.1', 'angle=45', 'amplitude=0', 'sharpness=0.4', 'anisotropy=0.8',
#@gmic : 'alpha=0.6', 'sigma=1.1' and 'cut_low=cut_high=0'.
#@gmic : $ image.jpg --marble ,
marble : -skip ${1=0.2},${2=0.1},${3=45},${4=0},${5=0.4},${6=0.8},${7=0.6},${8=1.1},${9=0%},${10=100%}
  -e[^-1] "Generate a marble like pattern. Image weight $1, pattern weight $2, angle $3°, amplitude $4, sharpness $5, anisotropy $6, alpha $7, sigma $8, cut ($9,$10)."
  -v - sx={$2*sin($3*pi/180)} sy={$2*cos($3*pi/180)} -f sin(x*$sx+y*$sy+i*$1)
  -if {$4} -smooth $4,$5,$6,$7,$8 -endif
  -c $9,$10 -n 0,255
  -v +

#@gmic maze : _width>0,_height>0,_cell_size>0
#@gmic : Generate maze with specified size.
#@gmic : $ -maze 30,20 -negative -n 0,255
maze : -check "isint(${1=15}) && $1>0 && isint(${2=$1}) && $2>0 && isint(${3=24}) && $3>0"
  -e[^-1] "Generate $1x$2 maze."
  -v -
  ({round(?($1-1))},{round(?($2-1))})  # Starting cell.
  $1,$2,1,1,15 --f[-1] 0 -a[-2,-1] c   # Starting maze data.
  -_generate_maze $1,$2
  -_render_maze[-1] $3
  -v +

_generate_maze :

  # Start opening walls.
  -do
    x=@{-2,-2} y=@{-2,-1}  # Coords of the current cell.
    -=[-1] 1,$x,$y,0,1     # Mark current cell as visited.

    # Check for neighboring cells that are candidate for opening wall, and select one random.
    is_candidate=0
    up=-1 -if {i($x,$y)&8" && "$y>0" && "!i($x,$y-1,0,1)} up=$x,{$y-1},8 is_candidate=1 -endif          # Up.
    down=-1 -if {i($x,$y)&4" && "$y<$2-1" && "!i($x,$y+1,0,1)} down=$x,{$y+1},4 is_candidate=1 -endif   # Down.
    left=-1 -if {i($x,$y)&2" && "$x>0" && "!i($x-1,$y,0,1)} left={$x-1},$y,2 is_candidate=1 -endif      # Left.
    right=-1 -if {i($x,$y)&1" && "$x<$1-1" && "!i($x+1,$y,0,1)} right={$x+1},$y,1 is_candidate=1 -endif # Right.
    -if $is_candidate
      ($up,$down,$left,$right) -discard[-1] -1 -r[-1] 3,{h/3},1,1,-1 -shift[-1] 0,{?(4)},0,0,2 -lines[-1] 0,0 -mv[-1] -2
    -endif

    # Remove wall between the current and chosen neighboring cells.
    -if $is_candidate
      -if {@{-2,-1}==8}   -=[-1] {i($x,$y)&7},$x,$y -=[-1] {i($x,$y-1)&11},$x,{$y-1}   # Remove up wall.
      -elif {@{-2,-1}==4} -=[-1] {i($x,$y)&11},$x,$y -=[-1] {i($x,$y+1)&7},$x,{$y+1}   # Remove down wall.
      -elif {@{-2,-1}==2} -=[-1] {i($x,$y)&13},$x,$y -=[-1] {i($x-1,$y)&14},{$x-1},$y  # Remove left wall.
      -else               -=[-1] {i($x,$y)&14},$x,$y -=[-1] {i($x+1,$y)&13},{$x+1},$y  # Remove right wall.
      -endif
      -z[-2] 0,1 -a[-3,-2] y  # Add neighboring cell to stack of cells to explore.
    -else # No candidate : remove current cell from cells to explore.
      -if {@{-2,h}==1} -break -endif
      -lines[-2] 0,{@{-2,h}-2}
    -endif
  -while 1
  -rm[-2] -channels[-1] 0

_render_maze :
  # Create the 16 configurations of walls.
  -i[0] $1,$1 -i[1] [0]x15
  -line[8-15] 0,0,100%,0,1,1
  -line[4-7,12-15] 0,100%,100%,100%,1,1
  -line[2-3,6-7,10-11,14-15] 0,0,0,100%,1,1
  -line[1-15:2] 100%,0,100%,100%,1,1
  # Map the wall data with them.
  -a[0-15] x -r[-1] {w*$1},{h*$1} -*[-1] $1 -channels[-1] 0,1
  $1,$1,1,1,x $1,$1,1,1,y -a[-2,-1] c -r[-1] [-2],[-2],1,2,0,2 -+[-2,-1]
  -warp[-2] [-1],0,0,0 -rm[-1]

#@gmic maze_mask : _cellsize>0
#@gmic : Generate maze according to size and shape of selected mask images.
#@gmic : Mask may contain disconnected shapes.
#@gmic : $ 1 -text "G'MIC",0,0,57,1,1 -dilate 3 -autocrop 0 -frame 1,1,0 -maze_mask 8 -dilate 3 -negative -* 255
maze_mask : -check "isint(${1=24}) && $1>0"
  -e[^-1] "Generate masked maze from image$? with cell size $1."
  -v - -norm -t 50% -repeat @# -l[$>]
    -do
      --rand[0] 0,1 -*[-1] [0] ({xM},{yM}) -rm[-2]  # Select one starting point in the mask.
      --flood[0] @-1,0,0,0,1,2 -t[-1] 2 --negative[-1] -*[-2] 15 -a[-2,-1] c
      -flood[0] @-2,0,0,0,1,0
      -_generate_maze {w},{h}
    -while @{0,M}
    -rm[0] -+ -_render_maze[-1] $1
  -endl -done -v +

#@gmic piechart : label_height>=0,label_R,label_G,label_B,"label1",value1,R1,G1,B1,...,"labelN",valueN,RN,GN,BN
#@gmic : Draw pie chart on selected (RGB) images.
#@gmic : $ image.jpg -piechart 25,0,0,0,"Red",55,255,0,0,"Green",40,0,255,0,"Blue",30,128,128,255,"Other",5,128,128,128
piechart : -check $1>=0
  -e[^-1] "Draw pie chart on image$?, with label height $1 and color ($2,$3,$4)."
  -v - -repeat @#
    -ellipse[-1] 50%,50%,{w/2-1},{h/2-1},0,1,1
    -ellipse[-1] 50%,50%,{w/2-1},{h/2-1},0,1,0xFFFFFFFF
    (${6--1:5}) -normalize_sum[-1]
    theta=0
    -repeat {w}
      xe={0.5*@{-2,w}*(1+cos($theta))}
      ye={0.5*@{-2,h}*(1+sin($theta))}
      -line[-2] 50%,50%,$xe,$ye
      theta={$theta-2*pi*i($>)}
    -done
    theta=0
    -repeat {w} -if {i($>)}
      ntheta={$theta-2*pi*i($>)}
      xc={0.5*@{-2,w}*(1+0.5*cos(0.5*($ntheta+$theta)))}
      yc={0.5*@{-2,h}*(1+0.5*sin(0.5*($ntheta+$theta)))}
      xf={0.5*@{-2,w}*(1+0.8*cos(0.5*($ntheta+$theta)))}
      yf={0.5*@{-2,h}*(1+0.8*sin(0.5*($ntheta+$theta)))}
      -flood[-2] $xf,$yf,0,0,0,1,@{-arg\ {7+5*$>}-{9+5*$>},"$*"}
      -if {abs($ntheta-$theta)>0.1}
        0 -text[-1] @{-arg\ {5+5*$>},"$*"},0,0,$1,1,1
        ($2^$3^$4) -r[-1] [-2],[-2],1,3 -*[-1] [-2]
        -j[-4] [-1],{$xc-w/2},{$yc-h/2},0,0,1,[-2]
        -rm[-2,-1]
      -endif
      theta=$ntheta
    -endif -done
    -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic polka_dots : diameter>=0,_density,_offset1,_offset2,_angle,_aliasing,_shading,_opacity,_color,...
#@gmic : Draw dots pattern on selected images.
#@gmic : Default values : 'density=20', 'offset1=offset2=50', 'angle=0', 'aliasing=10', 'shading=1', 'opacity=1' and 'color=255'.
#@gmic : $ image.jpg -polka_dots 10,15,0,0,20,10,1,0.5,0,128,255
polka_dots : -check $1>=0 -skip ${2=20},${3=50},${4=50},${5=0},${6=10},${7=1},${8=1},${9=255}
  -e[^-1] "Draw polka dots on image$?, with diameter $1, density $2, angle $3°, shift ($4,$5), aliasing $6 and shading $7."
  -v - theta={$5*pi/180} ct={cos($theta)} st={sin($theta)} mid1={$1/2} mid2={$2/2}
  -i[0] (${9--1}) -y[0] c
  -repeat {@#-1}
    WH={max(w,h)}
    100%,100%,100%,1,"xn = 100*x/"$WH"-$3; yn = 100*y/"$WH"-$4; \
                      xr = xn*"$ct"-yn*"$st"; yr = xn*"$st"+yn*"$ct"; \
                      xc = xr%$2-"$mid2"; yc = yr%$2-"$mid2"; \
                      "$mid1"-sqrt(xc*xc+yc*yc)"
    -*[-1] $6 -c[-1] 0,$7 -n[-1] 0,$8 (${9--1}) -y[-1] c -r[-1] [-2],[-2],[-2]
    -j[-3] [-1],0,0,0,0,1,[-2] -rm[-2,-1]
  -mv[-1] 1 -done -rm[0] -v +

#@gmic rorschach : 'smoothness[%]>=0','mirroring={ 0=none | 1=x | 2=y | 3=xy }
#@gmic : Render rorschach-like inkblots on selected images.
#@gmic : Default values : 'smoothness=5%' and 'mirroring=1'.
#@gmic : $ 400,400 -rorschach 3%
rorschach : -check ${1=5%}>=0 -skip ${2=1}
  -e[^-1] "Render rorschach-like inkblots on image$?, with smoothness $1 and "\
          @{"-if {$2==1} -u X -elif {$2==2} -u Y -elif {$2==3} -u XY -else -u no -endif"}\
          "-mirroring."
  -v -
  -if {$2==0} # No mirroring.
   -rand -1,1 -b $1 -t 0
  -elif {$2==1} # X-mirroring.
    -repeat @#
      w={w}
      -columns[-1] 0,{w/2-1} -rand[-1] -1,1 -b[-1] $1 -t[-1] 0
      --mirror[-1] x -if {$w%2} -columns[-1] 1,100% -endif -a[-2,-1] x
    -mv[-1] 0 -done
  -elif {$2==2} # Y-mirroring.
    -repeat @#
      h={h}
      -lines[-1] 0,{h/2-1} -rand[-1] -1,1 -b[-1] $1 -t[-1] 0
      --mirror[-1] y -if {$h%2} -lines[-1] 1,100% -endif -a[-2,-1] y
    -mv[-1] 0 -done
  -elif {$2==3} # XY-mirroring.
    -repeat @#
      w={w} h={h}
      -z[-1] 0,0,{w/2-1},{h/2-1} -rand[-1] -1,1 -b[-1] $1 -t[-1] 0
      --mirror[-1] x -if {$w%2} -columns[-1] 1,100% -endif -a[-2,-1] x
      --mirror[-1] y -if {$h%2} -lines[-1] 1,100% -endif -a[-2,-1] y
    -mv[-1] 0 -done
  -endif
  -v +

#@gmic sierpinski : recursion_level>=0
#@gmic : Draw Sierpinski triangle on selected images.
#@gmic : Default value : 'recursion_level=7'.
#@gmic : $ image.jpg -sierpinski 7
sierpinski : -check ${1=7}>=0 -skip ${2=50},${3=0},${4=0},${5=100},${6=100},${7=100}
  -e[^-1] "Draw Sierpinski triangle of degree $1 on image$?."
  -v - -_sierpinski ${2-7},$1  -v +

_sierpinski :
  -if {$7<=0} -polygon 3,$1%,$2%,$3%,$4%,$5%,$6%,1,255 -return -endif
  -_sierpinski $1,$2,{($1+$3)/2},{($2+$4)/2},{($1+$5)/2},{($2+$6)/2},{$7-1}
  -_sierpinski {($1+$3)/2},{($2+$4)/2},$3,$4,{($3+$5)/2},{($4+$6)/2},{$7-1}
  -_sierpinski {($1+$5)/2},{($2+$6)/2},$5,$6,{($3+$5)/2},{($4+$6)/2},{$7-1}

#@gmic snowflake : _recursion>=0,_x0,_y0,_x1,_y1,_x2,_y2,_opacity,_col1,..._colN
#@gmic : Draw a Koch snowflake on selected images.
#@gmic : Default values : 'recursion=4', 'x0=20', 'y0=70', 'x1=80', 'y1=70', 'x2=50', 'y2=10', 'opacity=1' and 'col1=255'.
#@gmic : $ image.jpg -snowflake 4
snowflake : -check ${1=4}>=0 -skip ${2=20},${3=70},${4=80},${5=70},${6=50},${7=10},${8=1},${9=255}
  -v -
  -polygon 3,$2%,$3%,$4%,$5%,$6%,$7%,${8--1}
  -_snowflake $1,$2,$3,$6,$7,${8--1}
  -_snowflake $1,$6,$7,$4,$5,${8--1}
  -_snowflake $1,$4,$5,$2,$3,${8--1}
  -v +

_snowflake :
  x0={$2+($4-$2)/3} y0={$3+($5-$3)/3}
  x1={$2+2*($4-$2)/3} y1={$3+2*($5-$3)/3}
  c={cos(-pi/3)} s={sin(-pi/3)}
  x2={$x0+($x1-$x0)*$c-($y1-$y0)*$s} y2={$y0+($x1-$x0)*$s+($y1-$y0)*$c}
  -polygon 3,$x0%,$y0%,$x1%,$y1%,$x2%,$y2%,${6--1}
  -if $1
    -_snowflake {$1-1},$2,$3,$x0,$y0,${6--1}
    -_snowflake {$1-1},$x0,$y0,$x2,$y2,${6--1}
    -_snowflake {$1-1},$x2,$y2,$x1,$y1,${6--1}
    -_snowflake {$1-1},$x1,$y1,$4,$5,${6--1}
  -endif

#@gmic text_outline : text,_x[%],_y[%],_font_height>0,_outline>=0,_opacity,_color1,..
#@gmic : Draw specified colored and outlined text string on selected images.
#@gmic : Default values : 'x=y=2', 'font_height=13', 'outline=2', 'opacity=1' and 'color1=255'.
#@gmic : $ image.jpg -text_outline "Hi there !",10,10,52,3
text_outline : -skip ${2=2},${3=2},${4=13},${5=2},${6=1},${7=255},${8=$-1},${9=$-1}
  -e[^-1] "Draw outlined text '$1' at position ($2,$3) on image$?, with font height $4, outline $5, opacity $6 and color ${7--1}."
  -v -
  -if $5
    1 -text[-1] "$1",0,0,$4,1,1 -expand_xy[-1] {1+$5},0 --dilate[-1] {2*$5+1}
    (${7--1}) -y[-1] c -r[-1] 2,1,1,100%,0,0,1 -map[-3] [-1] -rm[-1]
    -repeat {@#-2} -j[$>] [-2],$2,$3,0,0,$6,[-1] -done -rm[-2,-1]
  -else
    -text "$1",${2-4},${6--1}
  -endif
  -v +

#@gmic truchet : _scale>0,_radius>=0,_pattern_type={ 0=straight | 1=curved }
#@gmic : Fill selected images with random truchet patterns.
#@gmic : Default values : 'scale=32', 'radius=5' and 'pattern_type=1'.
#@gmic : $ 400,300 -truchet ,
truchet : -check "isint(${1=32}) && $1>0 && ${2=3}>=0" -skip ${3=1}
  -e[^-1] "Render "@{"-if $3 -u curved -else -u straight -endif"}" truchet patterns in image$?, with scale $1 and radius $2."
  -v - -repeat @#
    w={w} h={h} s={s} -rm[-1]
    $1,$1 -=[-1] 1,0,0 -=[-1] 1,100%,100% -distance[-1] 1,{1+$3} M={int(iM/2)} # Generate truchet pattern and its mirrored version.
    -t2[-1] {$M-$2/2-($1%2)},{$M+$2/2} --mirror[-1] y -a[-2,-1] x
    {round($w/$1,1,1)},{round($h/$1,1,1)} -rand[-1] 0,1 -t[-1] 50% -r[-1] {w*$1},{h*$1} -*[-1] $1
    -channels[-1] 0,1 (0,{$1-1}) -r[-1] $1,$1,1,1,3 --transpose[-1] -a[-2,-1] c -r[-1] [-2],0,2 -+[-2,-1]
    -warp[-2] [-1] -rm[-1]
    -t[-1] 50% -r[-1] $w,$h,1,1,0 -r[-1] 100%,100%,1,$s
  -mv[-1] 0 -done -v +

#@gmic turbulence : _radius>0,_octaves={1,2,3...,12},_alpha>0,_difference={-10,10},_mode={0,1,2,3}
#@gmic : Generate fractal noise or turbulence.
#@gmic : Default values : 'radius=32', 'octaves=6', 'alpha=3', 'difference=0' and 'mode=0'.
#@gmic : $ 400,400,1,3 -turbulence 16
turbulence : -check "${1=32}>0 && ${2=6}>0" -skip ${3=3},${4=0},${5=0}
  -e[^-1] "Generate fractal noise or turbulence with radius $1, octaves $2, damping per octave $3, difference $4 and mode $5."
  -v - -repeat @#
    -if {$4} [-1] -endif
    -f[-1] 0 --noise[-1] 10,0 -b[-1] $1,0
    -if {$5==0||$5==1} --[-1] @{-1,a} -abs[-1]
    -elif {$5==3||$5==4} -^[-1] 2
    -elif {$5==5} -^[-1] 3
    -endif
    -repeat {$2-1}
      --noise[-2] 10,0 -b[-1] {$1/2^$>},0
      -if {$5==0} --[-1] @{-1,a} -abs[-1]
      -elif {$5==4} -^[-1] 2
      -elif {$5==5} -^[-1] 3
      -endif
      -*[-2] $3 -+[-2--1]
    -done
    -n[-1] 0,255
    -rm[-2]
    -if {$4} -*[-1] $4 -mv[-2] 2 -- -n[-1] 0,255 -endif
  -mv[-1] 0 -done -v +

#---------------------------------
#
#@gmic :: 3d rendering
#
#---------------------------------

#@gmic animate3d : _width>0,_height>0,_dx,_dy,_dz,_zoom>=0,_filename
#@gmic : Animate selected 3d objects in a window.
animate3d : -skip ${1=640},${2=480},${3=0},${4=10},${5=0},"${7=""}" -check ${6=1}>=0
  -e[^-1] "Animate 3d object$?, in a $1x$2 window with angle velocities ($3,$4,$5)."
  -v - -repeat @#
    --n3d[$>] -*3d[-1] {$6*min($1,$2)/1.5} -c3d[-1] (0,0,0)
    frame=0
    -do
       --r3d[-2] 1,0,0,@{-1,0} -r3d[-1] 0,1,0,@{-2,1} -r3d[-1] 0,0,1,@{-2,2} ($3,$4,$5) -+[-3,-1]
       $1,$2,1,3,-1 -object3d[-1] [-2],50%,50%,0,1
       -if {narg("$7")}
         -to_rgba[-1] -replace_color[-1] 0,0,-1,-1,-1,255,64,64,64,0
         -o[-1] @{"-filename \"$7\","$>,$frame} frame={$frame+1}
       -else
         -replace[-1] -1,64
       -endif
       -w[-1] {w},{h},0,0,@{$>,n} -wait 20 -rm[-2,-1]
    -while {@!" && "!@{!,ESC}" && "!@{!,Q}} -rm[-1] -w 0
  -done -v +

#@gmic apply_camera3d : pos_x,pos_y,pos_z,target_x,target_y,target_z,up_x,up_y,up_z
#@gmic : Apply 3d camera matrix to selected 3d objects.
#@gmic : Default values : 'target_x=0', 'target_y=0', 'target_z=0', 'up_x=0', 'up_y=-1' and 'up_z=0'.
apply_camera3d : -skip ${4=0},${5=0},${6=0},${7=0},${8=-1},${9=0}
  -e[^-1] "Apply 3d camera matrix to 3d object$?, with camera position ($1,$2,$3), target position ($4,$5,$6) and up-vector ($7,$8,$9)."
  -v -
  ({$4-$1}^{$5-$2}^{$6-$3})  # f.
  ($7^$8^$9)                 # up.
  -orientation[-2,-1]        # f/|f| and up/|up|.
  -_cross3d @-2,@-1          # s = f x up
  -_cross3d @-1,@-3          # u = s x f
  -rm[-3] -y[-3--1] x -mv[-2,-1] -3
  -a[-3--1] y -z[-1] 0,3  # Rotation matrix R.
  --3d[0--2] $1,$2,$3 -apply_pose3d[0--2] @-1 --3d[0--2] 0,0,800
  -rm[-1] -v +

_cross3d :
  ({$2*$6-$3*$5};{$3*$4-$1*$6};{$1*$5-$2*$4})

#@gmic apply_pose3d : p1,..,p12
#@gmic : Apply 3d pose matrix to selected 3d objects.
#@gmic : $ -torus3d 100,20 -apply_pose3d 0.152437,1.20666,-0.546366,0,-0.535962,0.559129,1.08531,0,1.21132,0.0955431,0.548966,0,0,0,-206,1 -snapshot3d 400
apply_pose3d :
  -e[^-1] "Apply 3d pose matrix [ $1,$2,$3,$4; $5,$6,$7,$8; $9,$10,$11,$12 ] to 3d object$?."
  -v - -repeat @# -l[$>] -if @{-is_3d}
    nbp=@{-1,6}
    --lines[-1] 8,{8+3*$nbp}
    -r[-1] 3,{h/3},1,1,-1 1,{h},1,1,1 -a[-2,-1] x -transpose[-1]
    -i[-2] ($1,$2,$3,$4;$5,$6,$7,$8;$9,$10,$11,$12) -**[-2,-1] -transpose[-1] -r[-1] 1,{3*h},1,1,-1
    -j[-2] [-1],0,8 -rm[-1]
  -else -error "Image ["{@#-$>-1}"] does not represent a 3d object."
  -endif -endl -done -v +

#@gmic balls3d : _size>0,_R,_G,_B,_opacity
#@gmic : Convert selected 3d objects into 3d ball sets.
#@gmic : $ image.jpg -luminance -resize2dy 40 -threshold 50% -* 255 -pointcloud3d -color3d[-1] 255,255,255 -balls3d 20
balls3d : -check "${1=32}>0" -skip ${2=255},${3=$2},${4=$3},${5=1}
  -e[^-1] "Convert 3d object$? into 3d ball sets, with size $1 and color ($2,$3,$4)."
  -v - -repeat @#
    nbv=@{-1,6}
    $1,$1,1,4 -ball[-1] $2,$3,$4

    # Create object header.
    -i (@{-2,0-5},$nbv,$nbv)

    # Create vertices.
    -lines[-3] 8,{7+$nbv*3} -mv[-3] @#

    # Create point primitives.
    -i 1,$nbv,1,1,1 (0;{$nbv-1}) -r[-1] 1,$nbv,1,1,3 -a[-2,-1] x

    # Create colored sprites.
    (-128;$1;$1;3) --to_rgb[0] -y[-1] y
    -i 1,{4*($nbv-1)} -f[-1] -128,0,0,0 -a[-3--1] y

    # Create opacity.
    (-128;$1;$1;1) -channels[-6] 3,3 -mv[-6] @# -y[-1] y -*[-1] $5
    -i 1,{4*($nbv-1)} -f[-1] -128,0,0,0 -a[-3--1] y

    # Append all data into a CImg3d object.
    -y[-5,-3] y -a[-5--1] y

  -mv[-1] 0 -done -v +

#@gmic circles3d : _radius>=0
#@gmic : Convert specified 3d objects to sets of 3d circles with specified radius.
#@gmic : $ image.jpg -luminance -resize2dy 40 -threshold 50% -* 255 -pointcloud3d -color3d[-1] 255,255,255 -circles3d 0.7
circles3d : -check ${1=1}>=0
  -e[^-1] "Convert 3d object$? to sets of 3d circles with radius $1."
  -v - -p3d 0
  -repeat @# -l[$>]
    nbv=@{-1,6} nbp=@{-1,7}
    -if {$nbv&&$nbp}
      --3d {$1/2},0,0 --+3d $1,0,0 -+3d nbp2=@{-1,7}
      -s3d -=[1] $nbp,0,1
      -r[3] 2,$nbp2,1,1,-1 -columns[3] 1,1 -s[3] y,2 -i[3] 1,$nbp,1,1,5 -a[3-5] x -columns[3] 0,5 -y[3] y
      -lines[4] 0,{3*$nbp-1} -lines[5] 0,{$nbp-1} -a y
    -endif
  -endl -done -v +

#@gmic colorcube3d
#@gmic : Generate 3d color wireframe cube.
#@gmic : $ -colorcube3d
colorcube3d :
  -e[^-1] "Generate 3d color wireframe cube."
  -v -
  -_colorcube3d 0,0,0,255,0,0 # Front segments.
  -_colorcube3d 0,0,0,0,255,0 -r3d[-1] 0,0,1,-90
  -_colorcube3d 0,255,0,255,255,0 -+3d[-1] 0,255,0
  -_colorcube3d 255,0,0,255,255,0 -r3d[-1] 0,0,1,-90 -+3d[-1] 255,0,0
  -_colorcube3d 0,0,255,255,0,255 # Back segments.
  -_colorcube3d 0,0,255,0,255,255 -r3d[-1] 0,0,1,-90
  -_colorcube3d 0,255,255,255,255,255 -+3d[-1] 0,255,0
  -_colorcube3d 255,0,255,255,255,255 -r3d[-1] 0,0,1,-90 -+3d[-1] 255,0,0
  -+3d[-4--1] -+3d[-1] 0,0,255
  -_colorcube3d 0,0,0,0,0,255 -r3d[-1] 0,1,0,90 # Side segments.
  -_colorcube3d 255,0,0,255,0,255 -r3d[-1] 0,1,0,90 -+3d[-1] 255,0,0
  -_colorcube3d 0,255,0,0,255,255 -r3d[-1] 0,1,0,90 -+3d[-1] 0,255,0
  -_colorcube3d 255,255,0,255,255,255 -r3d[-1] 0,1,0,90 -+3d[-1] 255,255,0
  -+3d[-9--1] # Merge all segments together.
  -v +

_colorcube3d :
  -line3d 0,0,0,255,0,0 ($1,$4^$2,$5^$3,$6) -r[-1] 256,1,1,3,3 -texturize3d[-2] [-1] -rm[-1]

#@gmic cup3d : _resolution>0
#@gmic : Generate a new 3d cup object.
#@gmic : $ -cup3d ,
cup3d : -check ${1=128}>0
  -e[^-1] "Generate a new 3d cup, with resolution $1."
  -v -
  100,200
  -ellipse[-1] 0%,0%,40%,40%,0,1,1
  -ellipse[-1] 0,0,35%,35%,0,1,0
  -polygon[-1] 4,0,45%,8%,45%,20%,90%,0,90%,1,1
  -ellipse[-1] 0%,100%,30%,10%,0,1,1 -b[-1] 0.1%
  -lathe3d[-1] $1,2
  -v +

#@gmic distribution3d
#@gmic : Generate 3d color distribution of selected images.
#@gmic : $ image.jpg -distribution3d -colorcube3d -add3d
distribution3d :
  -e[^-1] "Generate 3d color distribution of image$?."
  -v - -to_rgb -permute "cxyz" -y y
  -repeat @#
    nbp={h/3}
    -i[-2] (67.5;73.5;109.5;103.5;51.5;100.5;\          # Magick number for CImg3d.
            $nbp;$nbp)                                  # Number of vertices and primitives.
    (1,0;1,{$nbp-1}) -r[-1] 2,$nbp,1,1,3 -y[-1] y  # Primitive description.
    [-2]                                                # Colors.
    1,$nbp,1,1,1                                        # Opacities.
    -a[-5--1] y                                         # Build 3d object.
  -mv[-1] 0 -done -v +

#@gmic empty3d
#@gmic : Generate new empty 3d object.
#@gmic : $ -empty3d
empty3d :
  -e[^-1] "Generate new empty 3d object."
  -v - (67.5;73.5;109.5;103.5;51.5;100.5;0;0) -v +

#@gmic extrude3d : _depth>0,_resolution>0,_smoothness[%]>=0
#@gmic : Generated extruded 3d object from selected binary profiles.
#@gmic : Default values : 'depth=16', 'resolution=1024' and 'smoothness=0.5%'.
#@gmic : $ image.jpg -threshold 50% -extrude3d 16
extrude3d : -check "${1=16}>0 && ${2=1024}>0 && ${3=0.5%}>=0"
  -e[^-1] "Generate extruded 3d object from XY-profile$?, with depth $1, resolution $2 and smoothness $3."
  -v - -norm -n 0,1 -autocrop 0 -repeat @#
    wr={round(max(1,if(w>h,min($2,w),min($2,h)*w/h)))}
    hr={round(max(1,if(w>h,min($2,w)*h/w,min($2,h))))}
    fact={$1/max(w/$wr,h/$hr)}
    -b[-1] $3,0 -r[-1] $wr,$hr,1,1,2 -expand_xyz[-1] 1,0
    -isosurface3d[-1] 50% -*3d[-1] 1,1,$fact -rv3d[-1]
  -mv[-1] 0 -done -v +

#@gmic gmic3d
#@gmic : Generate a 3d G'MIC logo.
#@gmic : $ -gmic3d --primitives3d 1
gmic3d :
  -e[^-1] "Generate 3d G'MIC logo."
  -v -
  -text3d G,60,20,2 -col3d[-1] 16,64,255
  -text3d \',60,20,2 -+3d[-1] 30 -col3d[-1] 64,128,255
  -text3d M,60,20,2 -+3d[-1] 40 -col3d[-1] 96,196,255
  -text3d I,60,20,2 -+3d[-1] 70 -col3d[-1] 64,128,255
  -text3d C,60,20,2 -+3d[-1] 95 -col3d[-1] 16,64,255
  -sphere3d 8 -+3d[-1] 85,-10,15 -col3d[-1] 192,128,255
  -+3d[-6--1] -c3d[-1]
  -repeat 30
    -box3d {min(3+@{<,-1}/2,10)} -col3d[-1] {30*$>},{20+80*$>},{10*$>},0.5
    -r3d[-1] 1,1,1,{$>*12}
    -+3d[-1] {80*cos(0.5+1.02*$>*12*pi/180)},{30*sin(0.8+$>*12*pi/180)},{2*$>-75}
  -done
  -+3d[-30--1] -+3d[-1] 0,5,30 -+3d[-2--1]
  -v +

#@gmic gyroid3d : _resolution>0,_zoom
#@gmic : Generate 3d gyroid at (0,0,0), with specified resolution.
#@gmic : Default values : 'resolution=32' and 'zoom=5'.
#@gmic : $ -gyroid3d 48 --primitives3d 1
gyroid3d : -check ${1=32}>0 -skip ${2=5}
  -e[^-1] "Generate new 3d gyroid, with resolution $1 and range $2."
  -v -
  -isosurface3d "'\
    0.49*(\
    cos( 2*x + y + z - pi) + cos( 2*x - y + z - pi)\
    + cos(- 2*x + y - z - pi) + cos(- 2*x - y - z - pi)\
    + cos( x + 2*y + z - pi) + cos( x + 2*y - z - pi)\
    + cos(- x - 2*y + z - pi) + cos(- x - 2*y - z - pi)\
    + cos( x + y + 2*z - pi) + cos(- x + y + 2*z - pi)\
    + cos( x - y - 2*z - pi) + cos(- x - y - 2*z - pi)\
    + cos(- 2*x + y + z) + cos( 2*x + y - z)\
    + cos(- 2*x - y + z) + cos( 2*x - y - z)\
    + cos(- x + 2*y + z) + cos( x - 2*y + z)\
    + cos(- x + 2*y - z) + cos( x - 2*y - z)\
    + cos( x - y + 2*z) + cos( x + y - 2*z)\
    + cos(- x - y + 2*z) + cos(- x + y - 2*z)\
    ) + 0.27*( \
    cos(- 2*x + 2*y - pi) + cos( 2*x - 2*y - pi)\
    + cos( 2*x + 2*y - pi) + cos(- 2*x - 2*y - pi)\
    + cos(- 2*y + 2*z - pi) + cos( 2*y - 2*z - pi)\
    + cos( 2*y + 2*z - pi) + cos(- 2*y - 2*z - pi)\
    + cos(- 2*z + 2*x - pi) + cos( 2*z - 2*x - pi)\
    + cos( 2*z + 2*x - pi) + cos(- 2*z - 2*x - pi)\
    ) - 0.69'",0,{-$2},{-$2},{-$2},$2,$2,$2,$1,$1,$1
  -c3d[-1] -n3d[-1]
  -v +

#@gmic histogram3d
#@gmic : Generate 3d color histogram of selected images.
#@gmic : $ image.jpg -histogram3d -colorcube3d -add3d
histogram3d :
  -e[^-1] "Generate 3d color histogram of image$?."
  -v - -to_rgb -repeat @#
    -r[-1] {w*h},3,1,1,-1 -pointcloud[-1] 1 -n[-1] 0,255 -map[-1] 3 -pointcloud3d[-1]
  -mv[-1] 0 -done -v +

#@gmic image6cube3d
#@gmic : Generate 3d mapped cubes from selected sets of 6 selected images.
#@gmic : $ image.jpg -animate flower,"30,0","30,5",6 -image6cube3d
image6cube3d :
  -e[^-1] "Generate 3d mapped cubes from sets of image$?."
  -v - M={max(@{-max_wh})} -r $M,$M,1,3 -imageplane3d -n3d -c3d -repeat {int(@#/6)}
    -+3d[-6] 0,0,-0.5
    -r3d[-5] 1,0,0,180 -+3d[-5] 0,0,0.5
    -r3d[-4] 0,1,0,-90 -+3d[-4] -0.5,0,0
    -r3d[-3] 0,1,0,90 -+3d[-3] 0.5,0,0
    -r3d[-2] 1,0,0,90 -+3d[-2] 0,-0.5,0
    -r3d[-1] 1,0,0,-90 -+3d[-1] 0,0.5,0
    -+3d[-6--1]
  -mv[-1] 0 -done -v +

#@gmic imagecube3d
#@gmic : Generate 3d mapped cubes from selected images.
#@gmic : $ image.jpg -imagecube3d
imagecube3d :
  -e[^-1] "Generate 3d mapped cubes from image$?."
  -v - -repeat @#
    w1={w-1} h1={h-1}
    -i[-2] (67.5;73.5;109.5;103.5;51.5;100.5;\  # Magick number for CImg3d.
            8;6;\                               # Number of vertices and primitives.
            -0.5;-0.5;-0.5;\                    # Vertex coordinates.
            0.5;-0.5;-0.5;\
            0.5;0.5;-0.5;\
            -0.5;0.5;-0.5;\
            -0.5;-0.5;0.5;\
            0.5;-0.5;0.5;\
            0.5;0.5;0.5;\
            -0.5;0.5;0.5;\
            12;0;3;2;1;0;0;0;$h1;$w1;$h1;$w1;0;\    # Primitives description.
            12;1;2;6;5;0;0;0;$h1;$w1;$h1;$w1;0;\
            12;5;6;7;4;0;0;0;$h1;$w1;$h1;$w1;0;\
            12;4;7;3;0;0;0;0;$h1;$w1;$h1;$w1;0;\
            12;4;0;1;5;0;0;0;$h1;$w1;$h1;$w1;0;\
            12;3;7;6;2;0;0;0;$h1;$w1;$h1;$w1;0;\
            -128;{w};{h};{s})       # Texture map for the first face.
    -y[-1] y
    (-128;0;0;0;-128;0;0;0;-128;0;0;0;-128;0;0;0;-128;0;0;0;1;1;1;1;1;1)  # Other faces and opacities.
    -a[-3--1] y
  -mv[-1] 0 -done -v +

#@gmic imageplane3d
#@gmic : Generate 3d mapped planes from selected images.
#@gmic : $ image.jpg -imageplane3d
imageplane3d :
  -e[^-1] "Generate 3d mapped planes from image$?."
  -v - -repeat @#
    w1={w-1} h1={h-1}
    -i[-2] (67.5;73.5;109.5;103.5;51.5;100.5;\   # Magick number for CImg3d.
            4;1;\                                # Number of vertices and primitives.
            0;0;0;\                              # Vertex coordinates.
            {w};0;0;\
            {w};{h};0;\
            {0};{h};0;\
            12;0;3;2;1;0;0;0;$h1;$w1;$h1;$w1;0;\ # Primitives description.
            -128;{w};{h};{s})                    # Texture map.
    -y[-1] y
    (1)  # Opacity.
    -a[-3--1] y
  -mv[-1] 0 -done -v +

#@gmic imagepyramid3d
#@gmic : Generate 3d mapped pyramides from selected images.
#@gmic : $ image.jpg -imagepyramid3d
imagepyramid3d :
  -e[^-1] "Generate 3d mapped pyramids from image$?."
  -v - -repeat @#
    w1={w-1} h1={h-1} w2={w/2}
    -i[-2] (67.5;73.5;109.5;103.5;51.5;100.5;\  # Magick number for CImg3d.
            5;5;\                               # Number of vertices and primitives.
            -0.5;-0.5;-0.5;\                    # Vertex coordinates.
            0.5;-0.5;-0.5;\
            0.5;0.5;-0.5;\
            -0.5;0.5;-0.5;\
            0;0;0.5;\
            12;0;3;2;1;0;0;0;$h1;$w1;$h1;$w1;0;\    # Primitives description.
            9;0;4;3;0;$h1;$w2;0;$w1;$h1;\
            9;1;4;0;0;$h1;$w2;0;$w1;$h1;\
            9;2;4;1;0;$h1;$w2;0;$w1;$h1;\
            9;3;4;2;0;$h1;$w2;0;$w1;$h1;\
            -128;{w};{h};{s})                   # Texture map for the first face.
    -y[-1] y
    (-128;0;0;0;-128;0;0;0;-128;0;0;0;-128;0;0;0;1;1;1;1;1)  # Other faces and opacities.
    -a[-3--1] y
  -mv[-1] 0 -done -v +

#@gmic imagerubik3d : _xy_tiles>=1,0<=xy_shift<=100,0<=z_shift<=100
#@gmic : Generate 3d mapped rubik's cubes from selected images.
#@gmic : Default values : 'xy_tiles=3', 'xy_shift=5' and 'z_shift=5'.
#@gmic : $ image.jpg -imagerubik3d ,
imagerubik3d : -check "${1=3}>=1 && ${2=5}>=0 && $2<=100 && ${3=5}>=0 && $3<=100"
  -e[^-1] "Generate 3d mapped rubik's cubes from image$? with $1 xy-tiles, xy-shift $2 and z-shift $3."
  -v - -repeat @# -l[$>]
    # Generate primary 3d side.
    ({'CImg3d'}) -+[-1] 0.5
    (8,5)
    (0,0,0;\
     100,0,0;\
     100,100,0;\
     0,100,0;\
     $2,$2,{-$3};\
     {100-$2},$2,{-$3};\
     {100-$2},{100-$2},{-$3};\
     $2,{100-$2},{-$3})
    (4,4,7,6,5;\
     4,0,4,5,1;\
     4,3,2,6,7;\
     4,0,3,7,4;\
     4,1,5,6,2)
    3,5,1,1,200
    1,5,1,1,1
    -y[-6--1] y -a[-6--1] y
    -repeat {$1-1} --+3d[-1] 100 -done -+3d[-$1--1]   # Duplicate along X
    -repeat {$1-1} --+3d[-1] 0,100 -done -+3d[-$1--1] # Duplicate along Y
    -t3d[-1] [-2] -rm[-2]
    -/3d[-1] $1 --3d[-1] 50,50,50
    --r3d[-1] 0,1,0,-90 --r3d[-1] 0,1,0,-90 --r3d[-1] 0,1,0,-90  # Generate the 5 other sides.
    --r3d[-1] 0,0,1,-90 --r3d[-1] 0,0,1,180
    -+3d[-6--1]
  -endl -done -v +

#@gmic imagesphere3d : _resolution1>=3,_resolution2>=3
#@gmic : Generate 3d mapped sphere from selected images.
#@gmic : Default values : 'resolution1=32' and 'resolutions2=16'.
#@gmic : $ image.jpg -imagesphere3d 32,16
imagesphere3d : -check "${1=32}>=3 && ${2=16}>=3"
  -e[^-1] "Create new 3d mapped sphere from image$?, with resolutions ($1,$2)."
  -v - -to_rgb -repeat @#

    # Generate object header.
    tw={w-1} th={h-1}                    # Maximum texture xy-coordinates.
    nbv={2+$1*($2-2)}                    # Number of vertices.
    nbp={$1*($2-1)}                      # Number of primitives.
    (67.5;73.5;109.5;103.5;51.5;100.5;\  # Magick number for CImg3d.
     $nbv;$nbp)                          # Number of vertices and primitives.

    # Define sphere vertices.
    (0;0;1) (0;0;-1) (0,{2*pi};0,{2*pi}^0,0;{pi},{pi})
    -r[-1] {$1+1},$2,1,2,3 -z[-1] 0,1,{w-2},{h-2} -s[-1] c
    --sin[-1] --sin[-3] -*[-2,-1] --cos[-2] -sin[-3] -cos[-4] -*[-4,-3]
    -a[-3--1] c -permute[-1] cxyz -y[-1] y -a[-3--1] y

    # Define sphere primitives (triangles and quadrangles).
    -repeat $1
      tx0={$>*$tw/$1} tx1={($>+1)*$tw/$1} ty1={$th/($2-1)}
      (9;0;{2+$>};{2+($>+1)%$1};{$tw/2};0;$tx0;$ty1;$tx1;$ty1) # Textured triangle from 1st pole.
      -repeat {$2-3}
        ty0=$ty1 ty1={($>+2)*$th/($2-1)} i0={2+$>*$1+@{>,-2}} i1={2+$>*$1+(@{>,-2}+1)%$1}
        (12;$i0;{$i0+$1};{$i1+$1};$i1;$tx0;$ty0;$tx0;$ty1;$tx1;$ty1;$tx1;$ty0) # Textured quadrangle.
      -done
      (9;1;{2+$1*($2-3)+($>+1)%$1};{2+$1*($2-3)+$>};{$tw/2};$th;$tx1;$ty1;$tx0;$ty1) # Textured triangle from 2nd pole.
    -done
    -a[-$nbp--1] y

    # Define sphere textures, opacities and generate object.
    -mv[-4] @# -i[-2] (-128;{w};{h};3) -y[-1] y 1,{4*($nbp-1)},1,1,-128,0,0,0 1,$nbp,1,1,1 -a[-7--1] y
  -mv[-1] 0 -done -v +

#@gmic label_points3d : _label_size>0,_opacity
#@gmic : Add a numbered label to all vertices of selected 3d objects.
#@gmic : Default values : 'label_size=13' and 'opacity=0.8'.
#@gmic : $ -torus3d 100,40,6,6 -label_points3d 24,1 -mode3d 1
label_points3d : -check ${1=13}>0 -skip ${2=0.8}
  -e[^-1] "Label vertices of 3d object$?."
  -v - -repeat @#
    --p3d[$>] 0 -l[-1] -s3d -rm[-3--1]
    nbp=@{-2,0} -=[-2] $nbp,0,1                                 # Set correct number of primitives
    (1,0;1,{$nbp-1}) -r[-1] 2,$nbp,1,1,3 -r[-1] 1,{2*h},1,1,-1  # Create new primitive data
    -repeat $nbp                                                # Create texture labels as primitive colors.
      1 -text[-1] $>,0,0,$1,1,255,255,255 -autocrop[-1] 0
      -i[-2] (-128;{w};{h};3) -y[-1] y
    -done
    -repeat $nbp                                                # Create texture masks as primitive opacities.
      1 -text[-1] $>,0,0,$1,1,$2 -autocrop[-1] 0
      -i[-2] (-128;{w};{h};1) -y[-1] y
    -done
    -a y  # Merge final object data.
    -endl
    -+3d[-2,-1]
  -mv[-1] 0 -done -v +

#@gmic lathe3d : _resolution>0,_smoothness[%]>=0,_max_angle>=0
#@gmic : Generate 3d object from selected binary XY-profiles.
#@gmic : Default values : 'resolution=128', 'smoothness=0.5%' and 'max_angle=361'.
#@gmic : $ 300,300 -rand -1,1 -blur 40 -sign -normalize 0,255 -lathe3d ,
lathe3d : -check "${1=128}>0 && ${2=0.5%}>=0 && ${3=361}>=0"
  -e[^-1] "Generate lathed 3d object from XY-profile$?, with resolution $1, smoothness $2 and maximum angle $3°."
  -v - tmax={($3-180)*pi/180} -norm -n 0,1 -autocrop 0 -repeat @#
    wr={max(1,w2=2*w;if(w2>h,min($1,w2),min($1,h)*w2/h))}
    hr={max(1,w2=2*w;if(w2>h,min($1,w2)*h/w2,min($1,h)))}
    rmax={sqrt(($wr)^2+($hr)^2)/2}
    $wr,1,$wr,1,"xc=x-w/2; zc=z-d/2; t=atan2(zc,xc); if(t>"$tmax","$rmax",sqrt(xc*xc+zc*zc))"
    -*[-1] {2*(@{-2,w}-1)/(w-1)} -r[-1] $wr,$hr,$wr
    (0;{@{-2,h}-1}) -r[-1] $wr,$hr,$wr,1,3 -a[-2--1] c
    -warp[-2] [-1],0,1,0 -rm[-1] -expand_xyz[-1] 10,0
    -b[-1] $2 -isosurface3d[-1] 50% -rv3d[-1]
  -mv[-1] 0 -done -v +

#@gmic lissajous3d : resolution>1,a,A,b,B,c,C
#@gmic : Generate 3d lissajous curves (x(t)=sin(a*t+A*2*pi),y(t)=sin(b*t+B*2*pi),z(t)=sin(c*t+C*2*pi)).
#@gmic : Default values : 'resolution=1024', 'a=2', 'A=0', 'b=1', 'B=0', 'c=0' and 'C=0'.
#@gmic : $ -lissajous3d ,
lissajous3d : -check ${1=1024}>1 -skip ${2=2},${3=0},${4=1},${5=0},${6=0},${7=0}
  -e[^-1] "Generate 3d lissajous curve, with resolution $1, (a,A)=($2,$3), (b,B)=($4,$5) and (c,C)=($6,$7)."
  -v -
  res={round($1)}

  # Define object header and vertices.
  (67.5;73.5;109.5;103.5;51.5;100.5;$res;{$res-1})
  (0,{2*pi}) -r[-1] $res,1,1,1,3 [-1]x2
  -*[-3] $2 -+[-3] {$3*2*pi} -*[-2] $4 -+[-2] {$5*2*pi} -*[-1] $6 -+[-1] {$7*2*pi}
  -a[-3--1] y -sin[-1] -transpose[-1] -r[-1] 1,{w*h},1,1,-1

  # Define object primitives, colors and opacities.
  1,{$res-1},1,1,2 (0;{$res-2}) -r[-1] 1,{$res-1},1,1,3 --+[-1] 1 -a[-3--1] x -round[-1] 1 -r[-1] 1,{w*h},1,1,-1
  1,{3*($res-1)},1,1,200 1,{$res-1},1,1,1 -a[-5--1] y
  -v +

#@gmic parametric3d : _x(a,b),_y(a,b),_z(a,b),_amin,_amax,_bmin,_bmax,_res_a>0,_res_b>0,_res_x>0,_res_y>0,_res_z>0,_smoothness>=0,_isovalue>=0
#@gmic : Generate new 3d object from specified parametric surface (x(a,b),y(a,b),z(a,b)).
#@gmic : Default values : 'x=(2+cos(b))*sin(a)', 'y=(2+cos(b))*cos(a)', 'c=sin(b)', 'amin=-pi', 'amax='pi', 'bmin=-pi', 'bmax='pi',
#@gmic : 'res_a=512', 'res_b=res_a', 'res_x=64', 'res_y=res_x', 'res_z=res_y', 'smoothness=2%' and 'isovalue=10%'.
#@gmic : $ -parametric3d ,
parametric3d : -skip "${1=(2+cos(b))*sin(a)}","${2=(2+cos(b))*cos(a)}","${3=sin(b)}"
               -skip ${4={-pi}},${5={pi}},${6={-pi}},${7={pi}}
               -check "${8=512}>0 && ${9=$8}>0 && ${10=64}>0 && ${11=$10}>0 && ${12=$11}>0 && \
                       ${13=2%}>=0 && ${14=10%}>=0"
  -e[^-1] "Generate new 3d object from parametric surface ($1,$2,$3)."
  -v -
  # Compute (x(a,b),y(a,b),z(a,b)) and normalize it.
  ($4,$5;$4,$5^$6,$6;$7,$7) -r[-1] $8,$9,1,2,3 -channels[-1] 0,2
  -f[-1] "a=i(x,y,0,0);b=i(x,y,0,1);if(c==0,$1,if(c==1,$2,$3))"
  -sh[-1] 0,0 xmin={im} xmax={iM} -n[-1] 16,{$10-17} -rm[-1]
  -sh[-1] 1,1 ymin={im} ymax={iM} -n[-1] 16,{$11-17} -rm[-1]
  -sh[-1] 2,2 zmin={im} zmax={iM} -n[-1] 16,{$12-17} -rm[-1]
  -r[-1] {w*h},3,1,1,-1

  # Extract 3d surface.
  -pointcloud[-1] 1 -r[-1] $10,$11,$12,1,0 -b[-1] $13,0
  -isosurface3d[-1] $14
  -c3d[-1] -n3d[-1] -*3d[-1] {$xmax-$xmin},{$ymax-$ymin},{$zmax-$zmin}
  -v +

#@gmic pca_patch3d : _patch_size>0,_M>0,_N>0,_normalize_input={ 0 | 1 },_normalize_output={ 0 | 1 },_lambda_xy
#@gmic : Generate 3d patch-pca representation of selected images.
#@gmic : The 3d patch-pca is estimated from M patches on the input image, and displayed as a cloud of N 3d points.
#@gmic : Default values : 'patch_size=7', 'M=1000', 'N=3000', 'normalize_input=1', 'normalize_output=0', and 'lambda_xy=0'.
#@gmic : $ image.jpg -pca_patch3d 7
pca_patch3d : -check "isint(${1=7}) && $1>0 && isint(${2=1000}) && $2>0 && isint(${3=3000}) && $3>0" -skip ${4=1},${5=0},${6=0}
  -e[^-1] "Generate 3d patch-pca representation"@{"-if {@#>1} -u s -else -u \"\" -endif"}" of image$?, from $2 $1x$1 input patchs,
           with $3 output patchs, input normalization "@{"-if $4 -u enabled -else -u disabled -endif"}", output normalization
          "@{"-if $5 -u enabled -else -u disabled -endif"}" and lambda_xy $6."
  -v -
  P1={int($1/2)}       # Backward half-patch size.
  P2={$1-$P1-1}        # Forward half-patch size.

  -n 0,255 -round 1
  -repeat @# -l[$>]
    s={s}
    title=@{-1,n}

    # Pick set of M random located patchs.
    -repeat $2
      x={round(?(@{0,w}))}
      y={round(?(@{0,h}))}
      ({$6*$x};{$6*$y})
      --z[0] {$x-$P1},{$y-$P1},{$x+$P2},{$y+$P2},1
      -y[-1] y -a[-2,-1] y
    -done

    # Normalize patch coordinates by using average and standard deviation.
    --+[1--1] -/[-1] $2 --[1--2] [-1] -rm[-1]
    -a[1--1] x
    -if $4 -l[-1] -s y -/ 'sqrt(1e-8+iv)' -a y -endl -endif

    # Do PCA for dimension reduction.
    --transpose[-1] -**[-2,-1]
    -eigen[-1] -lines[-2] 0,2 -columns[-1] 0,2 -transpose[-1]
    -if $5 -sqrt[-2] -/[-2] @{-2,M} -r[-2] [-1] -/[-1] [-2] -endif
    -rm[-2]

    # Pick set of N random located patchs.
    -repeat $3
      x={round(?(@{0,w}))}
      y={round(?(@{0,h}))}
      ({$6*$x};{$6*$y})
      --z[0] {$x-$P1},{$y-$P1},{$x+$P2},{$y+$P2},1
      -y[-1] y -a[-2,-1] y
    -done

    # Generate 3d representation of the projected patch set.
    --a[2--1] x -**[1,-1] -transpose[1]                    # Vertex coordinates.
    -lines[2--1] 2,100%                                    # Colors
    -if {$s!=3}
      -r[2--1] $1,$1,1,{min(3,$s)},-1
      -r[2--1] $1,$1,1,3,{if($s!=1,0,1)}
      -y[2--1] y
    -endif
    -i[2--2] (-128;$1;$1;3) -a[2--1] y
    -rm[0]                                                 # Remove input image (now useless).
    -i[0] ({'CImg3d'})                                     # Header.
    -i[1] ($3;$3)                                          # Geometry.
    -i[3] 2,$3,1,1,if(x==0,1,y)                            # Primitives.
    1,$3,1,1,1                                             # Opacities.
    -y y -a[-6--1] y                                       # Merge as a 3d object.
    -nm[-1] $title

  -endl -done -v +

#@gmic pointcloud3d
#@gmic : Generate 3d point cloud from selected planar or volumetric images.
#@gmic : $ image.jpg -luminance -resize2dy 100 -threshold 50% -* 255 -pointcloud3d -color3d[-1] 255,255,255
pointcloud3d :
  -e[^-1] "Generate 3d point clouds from image$?."
  -v - -repeat @# -l[$>]
    -s z -repeat @# -l[$>]
      --norm -!=[-1] 0
      -i[-2] (1,{w};1,{w}^1,1;{h},{h}) -r[-2] [-1],[-1],1,2,3 -*[-2,-1] -round[-1] -permute[-1] cxyz
      -l[-1] -s -,0 -a y is_points=@# -endl
      -if $is_points
        --[-1] 1 -r[-1] 2,{h/2},1,1,-1 -permute[-1] cyzx --warp[-2] [-1],0,0 -rm[-3]
        -permute[-2] cyzx -i[-2] 1,{h},1,1,$> -a[-3,-2] x    # Coordinates.
        -i[-3] ({'CImg3d'}) -i[-3] ({h},{h})                 # Header and size.
        -i[-2] 1,{h},1,1,1 -i[-2] 1,{h},1,1,y -a[-3,-2] x    # Primitives.
        -permute[-1] cyzx                                    # Colors.
        -if {w==1} -r[-1] 3,{h},1,1
        -elif {w>3} -i[-2] 4,{h},1,1,-128,1,1,{w} -a[-2,-1] x
        -else -r[-1] 3,{h},1,1,0
        -endif
        1,{h},1,1,1                                          # Opacities.
        -y[-6--1] y -a[-6--1] y
      -else -rm -empty3d
      -endif
      -endl -done
    -+3d
  -endl -done -v +

#@gmic projections3d : _x[%],_y[%],_z[%],_is_bounding_box={ 0 | 1 }
#@gmic : Generate 3d xy,xz,yz projection planes from specified volumetric images.
projections3d : -skip ${1=50%},${2=50%},${3=50%},${4=1}
  -e[^-1] "Generate 3d xy,xz,yz projection planes from image$?."
  -v - -n 0,255 -repeat @#
    w={w} h={h} d={d}
    x={if(@{"-is_percent $1"},$1*w,$1)}
    y={if(@{"-is_percent $2"},$2*h,$2)}
    z={if(@{"-is_percent $3"},$3*d,$3)}
    --lines[-1] $2,$2 -r[-1] {w},{d},1,100%,-1
    --columns[-2] $1,$1 -permute[-1] zyxc
    -slices[-3] $3,$3 -r[-3--1] 100%,100%,1,3
    -imageplane3d[-3--1]
    -r3d[-1] 0,1,0,90 -r3d[-2] 1,0,0,-90
    -+3d[-3] 0,0,$z -+3d[-2] 0,$y,0 -+3d[-1] $x,0,0
    -+3d[-3--1] -o3d[-1] 0.8
    -if $4 -box3d $w,$h,$d -p3d[-1] 1 -o3d[-1] 0.4 -+3d[-2,-1] -endif
  -mv[-1] 0 -done -v +

#@gmic pyramid3d : width,height
#@gmic : Generate 3d pyramid at (0,0,0), with specified geometry.
#@gmic : $ -pyramid3d 100,100 --primitives3d 1 -color3d[-2] @{-RGB}
pyramid3d :
  -e[^-1] "Generate new 3d pyramid, with width $1 and height $2."
  -v -
  (67.5;73.5;109.5;103.5;51.5;100.5;\  # Magick number for CImg3d.
   5;5;\                               # Number of vertices and primitives.
   {-$1/2};{-$1/2};{-$2/2};\           # Vertex coordinates.
   {$1/2};{-$1/2};{-$2/2};\
   {$1/2};{$1/2};{-$2/2};\
   {-$1/2};{$1/2};{-$2/2};\
   0;0;{$2/2};\
   4;0;3;2;1;\                         # Primitives description.
   3;0;4;3;\
   3;1;4;0;\
   3;2;4;1;\
   3;3;4;2)
  1,15,1,1,200 1,5,1,1,1 -a[-3--1] y
  -v +

#@gmic sierpinski3d : _recursion_level>=0,_width,_height
#@gmic : Generate new 3d Sierpinski pyramid.
#@gmic : $ -sierpinski3d 3 --primitives3d 1 -color3d[-2] @{-RGB}
sierpinski3d : -check ${1=4}>=0 -skip ${2=1},${3=1}
  -e[^-1] "Generate new 3d Sierpinski pyramid of degree $1, with width $2 and height $3."
  -v - -l[] -_sierpinski3d {-$2/2},{-$2/2},{-$3/2},{$2/2},{-$2/2},{-$3/2},{$2/2},{$2/2},{-$3/2},{-$2/2},{$2/2},{-$3/2},0,0,{$3/2},$1 -+3d -endl -v +

_sierpinski3d :
  -if {$16<=0}
    (67.5;73.5;109.5;103.5;51.5;100.5;\
     5;5;\
     $1;$2;$3;\
     $4;$5;$6;\
     $7;$8;$9;\
     $10;$11;$12;\
     $13;$14;$15;\
     4;0;3;2;1;\
     3;0;4;3;\
     3;1;4;0;\
     3;2;4;1;\
     3;3;4;2)
    1,15,1,1,200 1,5,1,1,1 -a[-3--1] y
  -return -endif
  -_sierpinski3d $1,$2,$3,\
                 {($1+$4)/2},{($2+$5)/2},{($3+$6)/2},\
                 {($1+$4+$7+$10)/4},{($2+$5+$8+$11)/4},{($3+$6+$9+$12)/4},\
                 {($1+$10)/2},{($2+$11)/2},{($3+$12)/2},\
                 {($1+$13)/2},{($2+$14)/2},{($3+$15)/2},\
                 {$16-1}
  -_sierpinski3d {($1+$4)/2},{($2+$5)/2},{($3+$6)/2},\
                 $4,$5,$6,\
                 {($4+$7)/2},{($5+$8)/2},{($6+$9)/2},\
                 {($1+$4+$7+$10)/4},{($2+$5+$8+$11)/4},{($3+$6+$9+$12)/4},\
                 {($4+$13)/2},{($5+$14)/2},{($6+$15)/2},\
                 {$16-1}
  -_sierpinski3d {($1+$4+$7+$10)/4},{($2+$5+$8+$11)/4},{($3+$6+$9+$12)/4},\
                 {($4+$7)/2},{($5+$8)/2},{($6+$9)/2},\
                 $7,$8,$9,\
                 {($7+$10)/2},{($8+$11)/2},{($9+$12)/2},\
                 {($7+$13)/2},{($8+$14)/2},{($9+$15)/2},\
                 {$16-1}
  -_sierpinski3d {($1+$10)/2},{($2+$11)/2},{($3+$12)/2},\
                 {($1+$4+$7+$10)/4},{($2+$5+$8+$11)/4},{($3+$6+$9+$12)/4},\
                 {($7+$10)/2},{($8+$11)/2},{($9+$12)/2},\
                 $10,$11,$12,\
                 {($10+$13)/2},{($11+$14)/2},{($12+$15)/2},\
                 {$16-1}
  -_sierpinski3d {($1+$13)/2},{($2+$14)/2},{($3+$15)/2},\
                 {($4+$13)/2},{($5+$14)/2},{($6+$15)/2},\
                 {($7+$13)/2},{($8+$14)/2},{($9+$15)/2},\
                 {($10+$13)/2},{($11+$14)/2},{($12+$15)/2},\
                 $13,$14,$15,\
                 {$16-1}

#@gmic snapshot3d : _size>0,_zoom>=0,_backgroundR,_backgroundG,_backgroundB
#@gmic : Create 2d snapshots of selected 3d objects.
#@gmic : Set 'zoom' to 0 to disable object auto-scaling.
#@gmic : Default values : 'size=512', 'zoom=1' and 'backgroundR=backgroundG=backgroundB=(undefined)'.
#@gmic : $ -torus3d 100,20 -snapshot3d 400,1.2,128,64,32
snapshot3d : -check "${1=512}>0 && ${2=1}>=0" -skip ${3=""}
  -if {narg($3)}
    -e[^-2,-1] "Create $1x$1 snapshot$? from 3d object$?, with zoom factor $2 and background color ${3--1}."
  -else
    -e[^-2,-1] "Create $1x$1 snapshot$? from 3d object$?, with zoom factor $2."
  -endif
  -v - -repeat @#
    -if {$2!=0} -c3d[-1] -n3d[-1] -*3d[-1] {3*$1*$2/4} -endif
    -if {narg($3)} (${3--1}) -y[-1] c -else 1,2,1,3,32,64,32,116,64,96 -endif -r[-1] $1,$1,1,3,3
    -object3d[-1] [-2],50%,50%,0,1,1 -name[-1] @{-2,n}
    -rm[-2]
  -mv[-1] 0 -done -v +

#@gmic spherical3d : _nb_azimuth>=3,_nb_zenith>=3,_radius_function(phi,theta)
#@gmic : Input 3d spherical object at (0,0,0), with specified geometry.
#@gmic : Default values : 'nb_zenith=nb_azimut=64' and 'radius_function="abs(1+0.5*cos(3*phi)*sin(4*theta))"'.
#@gmic : $ -spherical3d 64 --primitives3d 1
spherical3d : -check "${1=64}>=3 && ${2=$1}>=3" -skip "${3=abs(1+0.5*cos(3*phi)*sin(4*theta))}"
  -e[^-1] "Input 3d spherical object, with subdivisions ($1,$2) and height function '$3'."
  -v -
  ({'CImg3d'}) -y[-1] y # Magic number.
  n1={round($1)} n2={round($2)}

  # Define 3d vertices.
  $n1,{$n2-1},1,3,"phi=2*pi*(x+0.5)/w;\
                   theta=-pi/2+pi*(y+0.5)/h;\
                   cp=cos(phi);\
                   sp=sin(phi);\
                   ct=cos(theta);\
                   ($3)*if(c==0,ct*cp,if(c==1,ct*sp,sin(theta)))"
  -r[-1] {w*h},3,1,1,-1 -permute[-1] yxzc
  -i[-2] (0,0,{phi=0;theta=-pi/2;-$3};0,0,{phi=0;theta=pi/2;$3}) -a[-2,-1] y  # Add the two poles.
  nbv={h} -y[-1] y

  # Define 3d primitives.
  $n1,{$n2-2},1,4,"nx=(x+1)%w;ny=(y+1);2+if(c==0,x+y*"$n1",if(c==1,nx+y*"$n1",if(c==2,nx+ny*"$n1",x+ny*"$n1")))"
  -r[-1] {w*h},4,1,1,-1 -permute[-1] yxzc -i[-2] 1,{h},1,1,4 -a[-2,-1] x
  2,$n1,1,1,3,0 1,$n1,1,1,'y' --+[-1] 1 -%[-1] {h} 2,$n1,1,1,3,1 [-3,-2]  # Connect the two poles.
  -+[-5,-4] 2 -rv[-5,-4] -+[-2,-1] {$nbv-$n1} -a[-3--1] x -a[-4--2] x
  nbp={h+@{-2,h}+@{-3,h}}
  -y[-3--1] y -a[-3--1] y

  # Define other object informations (properties, colors and opacities).
  -i[-3] ($nbv;$nbp)
  1,{3*$nbp},1,1,200 1,$nbp,1,1,1 -a[-2,-1] y

  # Append as a 3d object.
  -a[-5--1] y -nm[-1] "[3d spherical surface '$3']"
  -v +

#@gmic superformula3d : resolution>1,m>=1,n1,n2,n3
#@gmic : Generate 2d superformula curve as a 3d object.
#@gmic : Default values : 'resolution=1024', 'm=8', 'n1=1', 'n2=5' and 'n3=8'.
#@gmic : $ -superformula3d ,
superformula3d : -check "${1=1024}>1 && ${2=8}>=1" -skip ${3=1},${4=5},${5=8}
  -e[^-1] "Generate 2d superformula curve, with resolution $1, m=$2 and (n1,n2,n3)=($3,$4,$5)."
  -v -
  res={round($1)}

  # Define object header and vertices.
  (67.5;73.5;109.5;103.5;51.5;100.5;$res;{$res-1})
  (0,{2*pi}) -r[-1] $res,1,1,1,3 [-1]

  -*[-1] {$2/4} --sin[-1] -cos[-2] -abs[-2,-1]
  -^[-2] $4 -^[-1] $5 -+[-2,-1] -^[-1] {-1/$3}
  --sin[-2] -cos[-3] -*[-1] [-2] -*[-3,-2] -n[-2,-1] -1,1
  -a[-2,-1] y -lines[-1] 0,2 -transpose[-1] -r[-1] 1,{w*h},1,1,-1

  # Define object primitives, colors and opacities.
  1,{$res-1},1,1,2 (0;{$res-2}) -r[-1] 1,{$res-1},1,1,3 --+[-1] 1 -a[-3--1] x -round[-1] 1 -r[-1] 1,{w*h},1,1,-1
  1,{3*($res-1)},1,1,200 1,{$res-1},1,1,1 -a[-5--1] y
  -v +

#@gmic text3d : text,_font_height>0,_depth>0,_smoothness
#@gmic : Generate a 3d text object from specified text.
#@gmic : Default values : 'font_height=57', 'depth=10' and 'smoothness=1.5'.
#@gmic : $ -text3d "G'MIC as a\n3D logo !"
text3d : -skip ${2=57},${3=10},${4=1.5}
  -e[^-1] "Generate 3d text object '$1' with size $2, depth $3 and smoothness $4."
  -v - 1 -text[-1] "$1",0,0,$2,1,1 -autocrop[-1] 0 -r[-1] 100%,100%,$3 -expand_xyz[-1] 10,0
  -b[-1] $4 -isosurface3d[-1] 40% -rv3d[-1] -v +

#@gmic weird3d : _resolution>0
#@gmic : Generate 3d weird object at (0,0,0), with specified resolution.
#@gmic : Default value : 'resolution=32'.
#@gmic : $ -weird3d 48
weird3d : -skip ${1=32}
  -e[^-1] "Generate new 3d weird object, with resolution $1."
  -v -
  -isosurface3d "'\
    T = 1.61803399;\
    2 - (cos(x + T*y) + cos(x - T*y) + cos(y + T*z) + cos(y - T*z) + cos(z - T*x) + cos(z + T*x))\
    '",0,-4.7,-4.7,-4.7,4.7,4.7,4.7,$1,$1,$1
  -c3d[-1] -n3d[-1]
  -v +

#-------------------------------
#
#@gmic :: Arrays and frames
#
#-------------------------------

#@gmic array : M>0,_N>0,_expand_type={0,1,2}
#@gmic : Create MxN array from selected images.
#@gmic : Default values : 'N=M' and 'expand_type=0'.
#@gmic : $ image.jpg -array 3,2,2
array : -skip ${2=$1},${3=0}
  -e[^-1] "Create $1x$2 array from image$?, with expand type $3."
  -v - -repeat @#
    -array_expand$3 $1,$2 [-1]x$1 -rm[-1] -a[-$1--1] x [-1]x$2 -rm[-1] -a[-$2--1] y
  -mv[-1] 0 -done -v +
array_expand0 :
  (100) ($1,$2) -/[-2] @{-1,M} -rm[-1] -r[-2] @-1%,@-1%,1,100%,2 -rm[-1]
array_expand1 :
  (100) ($1,$2) -/[-2] @{-1,m} -rm[-1] -r[-2] @-1%,@-1%,1,100%,2 -rm[-1]
array_expand2 :
  -skip $*

#@gmic array_fade : M>0,_N>0,0<=_fade_start<=100,0<=_fade_end<=100,_expand_type={0,1,2}
#@gmic : Create MxN array from selected images.
#@gmic : Default values : 'N=M', 'fade_start=60', 'fade_end=90' and 'expand_type=1'.
#@gmic : $ image.jpg -array_fade 3,2
array_fade : -skip ${2=$1},${3=60},${4=90},${5=1}
  -e[^-1] "Create $1x$2 array of ($3%,$4%) faded tiles from image$?, with expand type $5."
  -v - -repeat @#
    --shift[-1] 50%,50%,1,1,2 -mv[-1] -2 -fade_diamond[-2,-1] $3,$4 -array[-1] $1,$2,$5
  -mv[-1] 0 -done -v +

#@gmic array_mirror : N>=0,_dir={ 0=x | 1=y | 2=xy | 3=tri-xy },_expand_type={ 0 | 1 }
#@gmic : Create 2^Nx2^N array from selected images.
#@gmic : Default values : 'dir=2' and 'expand_type=0'.
#@gmic : $ image.jpg -array_mirror 2
array_mirror : -skip ${2=2},${3=0}
  -e[^-1] "Create a 2^$1x2^$1 mirrored-array from image$?, with expand type $2."
  -v - -repeat $1
    -if {$3==0}
      -if {$2>=3} -r 33%,33%,100%,100%,2
      -else -r 50%,50%,100%,100%,2
      -endif
    -endif
    -repeat @#
      -if {$2==0} --mirror[-1] x -a[-2,-1] x
      -elif {$2==1} --mirror[-1] y -a[-2,-1] y
      -else
        --mirror[-1] x -a[-2,-1] x --mirror[-1] y -a[-2,-1] y
        -if {$2==3} -r[-1] 150%,150%,1,100%,0,2,1,1 -endif
      -endif
    -mv[-1] 0 -done
  -done -v +

#@gmic array_pattern : M>0,_N>0,_density>=0,_angle>=0,_zoom>=0,_opacity,_expand_type={0,1,2}
#@gmic : Create random MxN array from selected images.
#@gmic : Default values : 'N=M', 'density=80', 'angle=180', 'zoom=30', 'opacity=1' and 'expand_type=0'.
#@gmic : $ image.jpg -array_pattern 10
array_pattern : -skip ${2=$1},${3=80},${4=180},${5=30},${6=1},${7=0}
  -e[^-1] "Create $1x$2 pattern array from image$?, with density $3, angle $4°, zoom $5, opacity $6 and expand type $7."
  -v - -repeat @#
    -array_expand$7 $1,$2 -set[-1] 0,0,0,0,3
    --z[-1] 0,0,0,0,0,0,0,100% ($1,$2) (@{-3,w},@{-3,h}) -*[-2,-1] -r[-2] @-1,1,100% -rm[-1]
    $1,$2,1,1,-1 -noise[-1] $3,2 -t[-1] 0 -y[-1] y
    -repeat $1 -repeat $2
      -if @{-1,0}
        ({?(-$5,$5)}) -+[-1] 100 --r[-4] @-1%,@-1%,1,100%,3 -rm[-2] --f[-1] 1
        (@{>,-2--1}) (@{-6,w},@{-6,h}) -*[-2,-1]
        ({?(-$4,$4)}) -rotate[-4] @-1,1,2 -rotate[-3] @-1,0,0 -rm[-1]
        -j[-5] [-3],@{-1},0,0,$6,[-2] -rm[-3--1]
      -endif
    -shift[-1] 0,-1 -done -done -rm[-3,-1]
  -mv[-1] 0 -done -v +

#@gmic array_random : Ms>0,_Ns>0,_Md>0,_Nd>0
#@gmic : Create MdxNd array of tiles from selected MsxNs source arrays.
#@gmic : Default values : 'Ns=Ms', 'Md=Ms' and 'Nd=Ns'.
#@gmic : $ image.jpg --array_random 8,8,15,10
array_random : -skip ${2=$1},${3=$1},${4=$2}
  -e[^-1] "Create $3x$4 array of tiles from $1x$2 array$?."
  -v - -repeat @#
    -l[-1] -split_tiles $1,$2
    -repeat $3 -repeat $4 [{?($1*$2-1)}] -done -done
    -rm[0-{$1*$2-1}] -append_tiles $3,$4
  -endl -mv[-1] 0 -done -v +

#@gmic frame : size_x[%]>=0,_size_y[%]>=0,_col1,...,_colN
#@gmic : Insert RGBA-colored frame in selected images.
#@gmic : Default values : 'size_y=size_x' and 'col1=255'.
#@gmic : $ image.jpg -frame 2,2,255 -frame 10,10,128,0,255
frame : -skip ${2=$1},${3=255},${4=$3},${5=$4}
  -e[^-1] "Insert $1x$2 outer frame in image$?, with color (${3--1})."
  -v - -repeat @#
    -if {$1} -i[-2] $1,[-1],[-1],[-1] -fc[-2] ${3--1} -nm[-2] @{-1,n} [-2] -a[-3--1] x -endif
    -if {$2} -i[-2] [-1],$2,[-1],[-1] -fc[-2] ${3--1} -nm[-2] @{-1,n} [-2] -a[-3--1] y -endif
  -mv[-1] 0 -done -v +

#@gmic frame_blur : _sharpness>0,_size>=0,_smoothness,_shade,_blur
#@gmic : Draw RGBA-colored round frame in selected images.
#@gmic : Default values : 'sharpness=10', 'size=30', 'smoothness=0', 'shade=1' and 'blur=3%'.
#@gmic : $ image.jpg -frame_blur 3,30,8,10%
frame_blur : -skip ${1=10},${2=30},${3=0},${4=1},${5=3%}
  -e[^-1] "Draw "\
          @{"-if $4 -u \"shaded \" -else -u \"\" -endif"}\
          "round frame on image$?, with sharpness $1, size $2, smoothness $3 and blur $5."
  -v - -to_rgba -repeat @#
    100%,100%,1,1,"-(abs(x/w-0.5)^$1 + abs(y/h-0.5)^$1)^(1/$1)" -t[-1] $2%
    -if $4 -distance[-1] 1 -n[-1] 0,1 -*[-1] -1 -+[-1] 1 -^[-1] {1/$4} -endif
    -b[-1] $3
    --b[-2] $5 -mv[-1] -3
    -compose_fade[-3--1]
  -mv[-1] 0 -done -v +

#@gmic frame_cube : _depth>=0,_x_center,_y_center,_left_side={0=normal | 1=mirror-x | 2=mirror-y | 3=mirror-xy},_right_side,_lower_side,_upper_side
#@gmic : Insert 3d frames in selected images.
#@gmic : Default values : 'depth=1', 'x_center=y_center=0' and 'left_side=right_side,lower_side=upper_side=0'.
#@gmic : $ image.jpg -frame_cube ,
frame_cube : -check "${1=1}>=0" -skip ${2=0},${3=0},${4=0},${5=0},${6=0},${7=0}
  -e[^-1] "Insert 3d frame in image$?, with depth $1, center ($2,$3) and orientations (${4--1})."
  -v - -repeat @# -l[$>] -split_opacity
    -if {@#==2} -frame_cube ${1--1} -a c  # Manage image with alpha-channel.
    -else
      m={max(w,h)} w={w} h={h} s={s}
      -imageplane3d -c3d -/3d[-1] $w,$h,1
      --_frame_cube[0] $4 -r3d[-1] 0,1,0,90 -+3d[-1] -0.5,0,-0.5  # Left side.
      --_frame_cube[0] $5 -r3d[-1] 0,1,0,-90 -+3d[-1] 0.5,0,-0.5  # Right side.
      --_frame_cube[0] $6 -r3d[-1] 1,0,0,90 -+3d[-1] 0,0.5,-0.5   # Lower side.
      --_frame_cube[0] $7 -r3d[-1] 1,0,0,-90 -+3d[-1] 0,-0.5,-0.5 # Upper side.
      -+3d 0,0,1 -+3d -*3d $w,$h,$m  # Append sides together.
      f=1000
      cx=$2*$w/2*($f+$m*$1)/$f
      cy=$3*$h/2*($f+$m*$1)/$f
      -s3d -r[2] 3,{@{2,h}/3},1,1,-1
      -f[2] "if(i(2,y)<0.5,i,i+if(x==0,"$cx",if(x==1,"$cy",($1-1)*"$m")))"
      -y[2] y -a y
      -*3d 2 {2*$w},{2*$h},1,$s -f3d {2*$f}
      mode=@* -m3d 2 -db3d 0 -object3d[-1] [-2],50%,50%,0,1,0 -rm[-2] -m3d @*
      -r $w,$h,1,100%,2
    -endif
  -endl -done
  -v +

_frame_cube :
  -if {$1==1} -r3d[-1] 0,1,0,180 -rv3d[-1]
  -elif {$1==2} -r3d[-1] 1,0,0,180 -rv3d[-1]
  -elif {$1==3} -r3d[-1] 0,0,1,180
  -endif

#@gmic frame_fuzzy : size_x>=0,_size_y>=0,_fuzzyness>=0,_smoothness>=0,_R,_G,_B,_A
#@gmic : Draw RGBA-colored fuzzy frame in selected images.
#@gmic : Default values : 'size_y=size_x', 'fuzzyness=5', 'smoothness=1' and 'R=G=B=A=255'.
#@gmic : $ image.jpg -frame_fuzzy 20
frame_fuzzy : -skip ${2=$1},${3=5},${4=1},${5=255},${6=$5},${7=$6},${8=255}
  -e[^-1] "Draw $1x$2 fuzzy frame on image$?, with fuzzyness $3, smoothness $4 and RGBA color ($5,$6,$7,$8)."
  -v - -to_rgba -repeat @#
    -i[0] ($1;$2) -*[0] 2 ($5^$6^$7^$8) -r[-1] [-2] 100%,100%
    -polygon[-1] 4,0,0,100%,0,100%,@{0,1},0,@{0,1},1,1
    -polygon[-1] 4,0,0,@{0,0},0,@{0,0},100%,0,100%,1,1
    -rm[0] -shift[-1] -$1,-$2,0,0,2 -spread[-1] $3 -b[-1] $4 -_fade 50,80
  -mv[-1] 0 -done -v +

#@gmic frame_pattern : M>=3,_pattern = { 0=first image | 1=self },_constrain_size = { 0 | 1 }
#@gmic : Insert selected pattern frame in selected images.
#@gmic : Default values : 'pattern=0' and 'constrain_size=0'.
#@gmic : $ image.jpg -frame_pattern 8
frame_pattern : -check $1>=3 -skip ${2=0},${3=0}
  -v - -to_colormode 0
  -if {@#==1||$2} # Self-framing
    -v + -e[^-1] "Insert $1x$1 self-pattern frame on image$?." -v -
    -repeat @#
      wh={w},{h}
      --r[-1] {w/($1-2)},{h/($1-2)},1,100%,2
      -r[-2] {$1*w},{$1*h},1,100%,0,0,0.5,0.5
      [-1]x{$1+2} -a[{-$1-2}--1] x -j[-3] [-1],0,0 -j[-3] [-1],0,{@{-3,h}-1-h} -rm[-1]
      [-1]x{$1+1} -a[{-$1-2}--1] y -j[-2] [-1],0,0 -j[-2] [-1],{@{-2,w}-1-w} -rm[-1]
      -if $3 -r[-1] $wh,1,100%,2 -endif
    -mv[-1] 0 -done
  -else # Frame from image[0]
    -v + -e[^-1] "Insert $1x$1 pattern frame on image$?, using first image." -v -
    -repeat {@#-1}
      wh={w},{h}
      --r[0] {w/($1-2)},{h/($1-2)},1,100%,2
      -r[-2] {@{-2,w}+2*w},{@{-2,h}+2*h},1,100%,0,0,0.5,0.5
      [-1]x{$1+2} -a[{-$1-2}--1] x -j[-3] [-1],0,0 -j[-3] [-1],0,{@{-3,h}-1-h} -rm[-1]
      [-1]x{$1+1} -a[{-$1-2}--1] y -j[-2] [-1],0,0 -j[-2] [-1],{@{-2,w}-1-w} -rm[-1]
      -if $3 -r[-1] $wh,1,100%,2 -endif
    -mv[-1] 1 -done -rm[0]
  -endif
  -v +

#@gmic frame_round : _sharpness>0,_size>=0,_smoothness,_shade,_R,_G,_B,_A
#@gmic : Draw RGBA-colored round frame in selected images.
#@gmic : Default values : 'sharpness=10', 'size=10', 'smoothness=0', 'shade=0' and 'R=G=B=A=255'.
#@gmic : $ image.jpg -frame_round 10
frame_round : -skip ${1=10},${2=10},${3=0},${4=0},${5=255},${6=$5},${7=$6},${8=255}
  -e[^-1] "Draw "\
          @{"-if $4 -u \"shaded \" -else -u \"\" -endif"}\
          "round frame on image$?, with sharpness $1, size $2, smoothness $3 and RGBA color ($5,$6,$7,$8)."
  -v - -to_rgba -repeat @#
    100%,100%,1,1,"-(abs(x/w-0.5)^$1 + abs(y/h-0.5)^$1)^(1/$1)" -t[-1] $2%
    -if $4 -distance[-1] 1 -n[-1] 0,1 -*[-1] -1 -+[-1] 1 -^[-1] {1/$4} -endif
    -b[-1] $3
    -i[-3] 100%,100%,1,4 -fc[-3] $5,$6,$7,$8
    -compose_fade[-3--1]
  -mv[-1] 0 -done -v +

#@gmic imagegrid : _M>0,_N>0
#@gmic : Create MxN image grid from selected images.
#@gmic : Default value : 'N=M'.
#@gmic : $ image.jpg -imagegrid 16
imagegrid : -skip ${2=$1}
  -e[^-1] "Create $1x$2 image grid from image$?."
  -v - -repeat @#
    ({w},{h}) ($1,$2) -/[-2,-1] -round[-1] 1 -r[-2] @-1,[-2],[-2],2 -rm[-1]
    ({w},{h}) ($1,$2) -*[-2,-1] -r[-2] @-1,[-2],[-2],2 -rm[-1]
    $1,$2,1,[-1],1 -shift[-1] 1,1 -r[-1] [-2],0,2 -*[-2,-1]
  -mv[-1] 0 -done -v +

#@gmic linearize_tiles : M>0,_N>0
#@gmic : Linearize MxN tiles on selected images.
#@gmic : Default value : 'N=M'.
#@gmic : $ image.jpg --linearize_tiles 16
linearize_tiles : -check "$1>0 && ${2=$1}>0"
  -e[^-1] "Linearize $1x$2 tiles on image$?."
  -v -
  -repeat @# -l[-1]
    s={s} -split_tiles $1,$2 -s c # Split as tiles for all channels.
    -repeat @#
      wh={w},{h}
      --f[-1] x --f[-1] y --f[-1] 1 -y[-4--1] y -a[-3--1] x
      -solve[-2] [-1] -rm[-1]
      -i $wh,1,1,@{-1,0}"*x + "@{-1,1}"*y + "@{-1,2} -rm[-2]
    -mv[-1] 0 -done
    -repeat {int(@#/$s)} -a[-$s--1] c -mv[-1] 0 -done -append_tiles $1,$2
  -endl -mv[-1] 0 -done -v +

#@gmic quadratize_tiles : M>0,_N>0
#@gmic : Quadratize MxN tiles on selected images.
#@gmic : Default value : 'N=M'.
#@gmic : $ image.jpg --quadratize_tiles 16
quadratize_tiles : -check "$1>0 && ${2=$1}>0"
  -e[^-1] "Quadratize $1x$2 tiles on image$?."
  -v -
  -repeat @# -l[-1]
    s={s} -split_tiles $1,$2 -s c # Split as tiles for all channels.
    -repeat @#
      wh={w},{h}
      --f[-1] x^2 --f[-1] y^2 --f[-1] x*y --f[-1] x --f[-1] y --f[-1] 1 -y[-7--1] y -a[-6--1] x
      -solve[-2] [-1] -rm[-1]
      -i $wh,1,1,@{-1,0}"*x^2 + "@{-1,1}"*y^2 + "@{-1,2}"*x*y +"@{-1,3}"*x + "@{-1,4}"*y + "@{-1,5} -rm[-2]
    -mv[-1] 0 -done
    -repeat {int(@#/$s)} -a[-$s--1] c -mv[-1] 0 -done -append_tiles $1,$2
  -endl -mv[-1] 0 -done -v +

#@gmic rotate_tiles : angle,_M>0,N>0
#@gmic : Apply MxN tiled-rotation effect on selected images.
#@gmic : Default values : 'M=8' and 'N=M'.
#@gmic : $ image.jpg -to_rgba -rotate_tiles 10,8 -drop_shadow 10,10 -display_rgba
rotate_tiles : -skip ${2=8},${3=$2}
  -e[^-1] "Apply $2x$3 tiled-rotation effect on image$?, with angle $1°."
  -v - -split_tiles $2,$3,1 -rotate $1 -append_tiles $2,$3 -v +

#@gmic shift_tiles : M>0,_N>0,_amplitude
#@gmic : Apply MxN tiled-shift effect on selected images.
#@gmic : Default values : 'N=M' and 'amplitude=20'.
#@gmic : $ image.jpg --shift_tiles 8,8,10
shift_tiles : -skip ${2=8},${3=20}
  -e[^-1] "Apply $1x$2 tiled-shift effect on image$?, with amplitude $3."
  -v - -repeat @#
    $1,$2,1,2 -noise[-1] $3 -r[-1] [-2],[-2],1,2 -warp[-2] [-1],1,1,0 -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic taquin : M>0,_N>0
#@gmic : Create MxN taquin puzzle from selected images.
#@gmic : Default value : 'N=M'.
#@gmic : $ image.jpg --taquin 8
taquin : -skip ${2=$1}
 -e[^-1] "Create $1x$2 taquin puzzle from image $?."
 -v - -repeat @# -l[-1]
   -split_tiles $1,$2,1 -repeat {$1*$2} -mv[$>] {?(@#)} -done -append_tiles $1,$2
 -endl -mv[-1] 0 -done -v +

#@gmic tunnel : _level>=0,_factor>0,_cx,_cy,_opacity.
#@gmic : Apply tunnel effect on selected images.
#@gmic : Default values : 'level=9', 'factor=80%', 'cx=cy=0.5' and 'opacity=1'.
#@gmic : $ image.jpg --tunnel 20
tunnel : -check "${1=9}>=0 && ${2=80%}>0" -skip ${3=0.5},${4=0.5},${5=0.1}
  -e[^-1] "Apply tunnel effect on image$?, with depth $1, factor $2, centering ($3,$4) and opacity $5."
  -v - -repeat @#
    -repeat $1 --r[-1] $2,$2,1,100%,5 -j[-2] [-1],{(@{-2,w}-w)*$3},{(@{-2,h}-h)*$4},0,0,$5 -rm[-1] -done
  -mv[-1] 0 -done -c 0,255 -v +

#-----------------------------
#
#@gmic :: Artistic
#
#-----------------------------

#@gmic cartoon : _smoothness,_sharpening,_threshold>=0,_thickness>=0,_color>=0,quantization>0
#@gmic : Apply cartoon effect on selected images.
#@gmic : Default values : 'smoothness=2', 'sharpening=200', 'threshold=15', 'thickness=0.25', 'color=1.5' and 'quantization=8'.
#@gmic : $ image.jpg --cartoon 3,80,15
cartoon : -skip ${1=2},${2=200},${3=15},${4=0.25},${5=1.5},${6=8}
  -e[^-1] "Apply cartoon effect on image$?, with smoothness $1, sharpening $2, threshold $3, thickness $4, color $5 and quantization $6."
  -v - -to_rgb -b $1 -sharpen $2,1 -c 0,255 -n 0,255 -repeat @#
    --edges[-1] $3 -b[-1] $4 -t[-1] 0.9
    -rgb2lab[-2] -s[-2] c -*[-3,-2] $5 -a[-4--2] c -lab2rgb[-2] -quantize[-2] $6 -n[-2] 0,255
    -*[-2,-1]
  -mv[-1] 0 -done -v +

#@gmic circlism : _radius_min>0,_radius_max>0,_smoothness[%]>=0,_radius_linearity>=0,_location_linearity>=0,_shape={0=squares | 1=diamonds | 2=circle }
#@gmic : Apply circlism effect on selected images (effect inspired by Ben Heine).
#@gmic : Default values : 'radius_min=2', 'radius_max=20', 'smoothness=1', 'radius_linearity=0.4', 'location_linearity=3' and 'shape=1'.
#@gmic : $ image.jpg --circlism ,
circlism : -check "${1=2}>0 && ${2=20}>0 && ${3=1}>=0 && ${4=0.4}>0 && ${5=3}>=0" -skip ${6=2}
  -e[^-1] "Apply circlism effect on image$?, with radii ($1,$2), smoothness $3, radius linearity $4 and location linearity $5.\n"
  -v - -repeat @#
    --gradient_norm[-1] -b[-1] $3 -n[-1] 0,1 --^[-1] $5 -^[-2] $4 sumg0=@{-1,+} 100%,100%
    it=0 failed=0 noedges=0 svg="-1,-1"
    -do
      --distance[-1] 1,3
      -if $noedges xyzc=@{-1,C} -else --*[-3,-1] xyzc=@{-1,C} -rm[-1] -endif
      n=@{-4,($xyzc)}
      x={arg(1,$xyzc)}
      y={arg(2,$xyzc)}
      r={min(max($1,$2*(1-$n)),sqrt(@{-1,($xyzc)})-2)}
      -rm[-1]
      -if {$r>=$1}
        -if {$6==2}  # Fill with circles.
          -ellipse[-1] $x,$y,$r,$r,0,1,1 -ellipse[-2] $x,$y,{$r+$1},{$r+$1},0,1,-1
        -elif {$6==1} # Fill with squares.
          x0={$x-$r/2} y0={$y-$r/2} x1={$x+$r/2} y1={$y+$r/2}
          -polygon[-1] 4,$x0,$y0,$x1,$y0,$x1,$y1,$x0,$y1,1,1
          x0={$x-($r+$1)/2} y0={$y-($r+$1)/2} x1={$x+($r+$1)/2} y1={$y+($r+$1)/2}
          -polygon[-2] 4,$x0,$y0,$x1,$y0,$x1,$y1,$x0,$y1,1,-1
        -else # Fill with diamonds.
          x0={round($x-$r/2)} y0={round($y-$r/2)} x1={round($x+$r/2)} y1={round($y+$r/2)}
          -polygon[-1] 4,$x0,$y,$x,$y0,$x1,$y,$x,$y1,1,1
          x0={round($x-($r+$1)/2)} y0={round($y-($r+$1)/2)} x1={round($x+($r+$1)/2)} y1={round($y+($r+$1)/2)}
          -polygon[-2] 4,$x0,$y,$x,$y0,$x1,$y,$x,$y1,1,-1
        -endif
        failed=0
      -else
        -=[-2] -1,$x,$y
        failed={$failed+1}
        -if {$failed==100} failed=0 -if $noedges n=-1 -else noedges=1 -endif -endif
      -endif
      it={$it+1}
      -if {!($it%50)}
        p={round(100*(($sumg0-@{-2,+})/@{-2,wh})^3)}
        -progress $p -v + -e[] "\r  "$p% -v -
      -endif
    -while {$n>=0}
    -rm[-3,-2] -progress -1
    -compose_shapeaverage
  -mv[-1] 0 -done -v +

#@gmic color_ellipses : _count>0,_radius>=0,_opacity>=0
#@gmic : Add random color ellipses to selected images.
#@gmic : Default values : 'count=400', 'radius=5' and 'opacity=0.1'.
#@gmic : $ image.jpg --color_ellipses ,,0.15
color_ellipses : -skip ${1=1400},${2=5},${3=0.1}
  -e[^-1] "Add $1 random color ellipses to image$?, with maximum radius $2 and opacity $1."
  -v - -repeat @#
    -repeat $1 -ellipse[-1] {?(0,100)}%,{?(0,100)}%,{?(0,$2)}%,{?(0,$2)}%,{?(0,360)},$3,{?(60,255)},{?(60,255)},{?(60,255)} -done
  -mv[-1] 0 -done -v +

#@gmic cubism : _nb_iter>=0,_bloc_size>0,_max_angle,_opacity,_smoothness>=0
#@gmic : Apply cubism effect on selected images.
#@gmic : Default values : 'nb_iter=160', 'bloc_size=10', 'max_angle=75', 'opacity=0.7' and 'smoothness=0'.
#@gmic : $ image.jpg --cubism ,
cubism : -skip ${1=160},${2=10},${3=75},${4=0.7},${5=0}
  -e[^-1] "Apply cubism effect on image$?, with $1 iterations, bloc size $2%, maximum angle $3°, opacity $4 and smoothness $5."
  -v - -repeat @#
    M={$2*max(w,h)/200}
    -repeat $1
      ({?(0,w)},{?(0,h)})
      --z[-2] {@{-1,0}-$M},{@{-1,1}-$M},{@{-1,0}+$M},{@{-1,1}+$M},1
      -b[-1] $5 --f[-1] 1 -rotate[-2,-1] {?(-$3,$3)},0,0
      -j[-4] [-2],{@{-3,0}-$M},{@{-3,1}-$M},0,0,$4,[-1] -rm[-3--1]
    -done
  -mv[-1] 0 -done -v +

#@gmic dotsbw : _nb_scales>=0,_resolution>0,_radius>=0
#@gmic : Apply B&W dots effect on selected images.
#@gmic : Default values : 'nb_scales=4', 'resolution=10' and 'radius=3'.
#@gmic : $ image.jpg --dotsbw 10,10,5
dotsbw : -check "${1=4}>=0 && ${2=10}>0 && ${3=3}>=0"
  -e[^-1] "Apply B&W dots effect on image$?, with $1 scale(s), resolution $2% and radius %3."
  -v - -r {max(1,w*$2/100)},{max(1,h*$2/100)},1,100%,2
  -repeat @#
    wh={w*100/$2},{h*100/$2} $wh,1,100%
    -repeat $1
      --t[-2] {100*($>+1)/($1+1)}%
      -r[-1] $wh,1,100%,4,0,0.5,0.5
      -b[-1] {$3*($>+1)/($1+1)},0
      -t[-1] 20%
      -or[-2,-1]
    -done -rm[-2]
  -mv[-1] 0 -done -v +

#@gmic draw_whirl : _amplitude>=0
#@gmic : Apply whirl drawing effect on selected images.
#@gmic : Default value : 'amplitude=100'.
#@gmic : $ image.jpg --draw_whirl ,
draw_whirl : -skip ${1=100}
  -e[^-1] "Apply whirl drawing effect on image$? with amplitude $1."
  -v - -repeat @#
    100%,100% -noise[-1] 70,2 -*[-1] 255 -r[-1] [-2] -and[-1,-2] -smooth[-1] $1,0,1,2,2
    -sqrt[-1] -n[-1] 0,255 -equalize[-1] 256
  -mv[-1] 0 -done -v +

#@gmic drawing : _amplitude>=0
#@gmic : Apply drawing effect on selected images.
#@gmic : Default value : 'amplitude=200'.
#@gmic : $ image.jpg --drawing ,
drawing : -skip ${1=200}
  -e[^-1] "Apply drawing effect on image$? with amplitude $1."
  -v - -to_rgb -repeat @#
    -smooth[-1] $1,0.2,1,3,3 -b[-1] 2 -sharpen[-1] 1000 [-1]
    -r[-2] 20,20,1,3,2 -equalize[-2] 256 -index[-1] [-2],1,1 -rm[-2]
  -mv[-1] 0 -done -v +

#@gmic drop_shadow : _offset_x[%],_offset_y[%],_smoothness[%]
#@gmic : Drop shadow behind selected images.
#@gmic : Default values : 'offset_x=20', 'offset_y=offset_x' and 'smoothness=5'.
#@gmic : $ image.jpg -drop_shadow 10,20 -expand_xy 20,0 -display_rgba
drop_shadow : -skip ${1=20},${2=$1},${3=5}
  -e[^-1] "Drop shadow behind image$?, with offsets ($1,$2) and smoothness $3."
  -v - -to_rgba -repeat @#
    -r[-1] 150%,150%,1,100%,0,0,0.5,0.5 -s[-1] c --b[-1] $3 -shift[-1] $1,$2 -or[-2,-1] -a[-4--1] c
    -autocrop 0,0,0,0
  -mv[-1] 0 -done -v +

#@gmic ellipsionism : _R>0[%],_r>0[%],_smoothness>=0[%],_opacity,_outline>0,_density>0
#@gmic : Apply ellipsionism filter to selected images.
#@gmic : Default values : 'R=10', 'r=3', 'smoothness=1%', 'opacity=0.7', 'outlise=8' and 'density=0.6'.
#@gmic : $ image.jpg --ellipsionism ,
ellipsionism : -check "${1=10}>0 && ${2=3}>0 && ${5=8}>0 && ${6=0.6}>0" -skip ${3=1%},${4=0.7}
  -e[^-1] "Apply ellipsionism filter to image$?, with radii ($1,$2), smoothness $3, opacity $4 and outline $5."
  -v - -to_rgba -repeat @#

    # Compute contour angle.
    --luminance[-1] -g[-1] xy -a[-2,-1] c -b[-1] $3 -orientation[-1]
    -sh[-1] 0,0 -sh[-2] 1,1 -atan2[-1] [-2] -*[-1] {180/pi} -+[-1] 90 -rm[-2,-1]
    -channels[-1] 1,1

    # Render ellipses.
    [-2],[-2],1,[-2]
    -repeat {$6*w*h/max($1,$2)}
      xy={?(w)},{?(h)}
      -ellipse[-1] $xy,$1,$2,@{-2,($xy)},$4,\
                   @{-3,($xy,0,0)},@{-3,($xy,0,1)},@{-3,($xy,0,2)},@{-3,($xy,0,3)}
      -ellipse[-1] $xy,$1,$2,@{-2,($xy)},$4,0x1,\
                   {@{-3,($xy,0,0)}/$5},{@{-3,($xy,0,1)}/$5},{@{-3,($xy,0,2)}/$5},{@{-3,($xy,0,3)}/$5}
    -done -rm[-2]

    # Renormalize and prepare next image.
    -n[-1] [-2] -compose_alpha[-2,-1]
  -mv[-1] 0 -done -v +

#@gmic fire_edges : _edges>=0,0<=_attenuation<=1,_smoothness>=0,_threshold>=0,_nb_frames>0,_starting_frame>=0,frame_skip>=0
#@gmic : Generate fire effect from edges of selected images.
#@gmic : Default values : 'edges=0.7', 'attenuation=0.25', 'smoothness=0.5', 'threshold=25', 'nb_frames=1', 'starting_frame=20' and 'frame_skip=0'.
#@gmic : $ image.jpg -fire_edges ,
fire_edges : -check "${1=0.7}>=0 && ${2=0.25}>=0 && $2<=1 && ${3=0.5}>=0 && ${4=25}>=0 && ${5=1}>0 && ${6=20}>=0 && ${7=0}>=0"
  -e[^-1] "Generate fire effect from edges of image$?, with edges $1, attenuation $2, smoothness $3, threshold $4, $5 frames, starting frame $6 and frame skip $7."
  -v - -repeat @# -l[$>]
    -norm --gradient_norm -n[-1] 0,1 -roundify[-1] $1 -f[0] 0
    (0,0,0;0,0,0;1,1,1;0,1,0) -*[-1] {(1-$2^4)/4}
    -repeat {$5*(1+$7)+$6}
      @{0,w},@{0,h} -rand[-1] 0,255 -*[-1] [1]
      -b[-1] $3
      -if $4 -t[-1] $4% -else -equalize[-1] 256 -endif
      -n[-1] 0,255
      -j[0] [-1],0,0,0,0,1,[1],1 -rm[-1]
      -correlate[0] [2]
      -if {$>>=$6" && "($>-$6)%($7+1)==0} [0] -endif
    -done
    -rm[0-2]
  -endl -done
  (0,255,255,255,255^0,0,255,255,255^0,0,0,128,255) -r[-1] 256,1,1,3,3
  -map[0--2] [-1] -rm[-1] -v +

#@gmic glow : _amplitude>=0
#@gmic : Add soft glow on selected images.
#@gmic : Default value : 'amplitude=1%'.
#@gmic : $ image.jpg --glow ,
glow : -skip ${1=1%}
  -e[^-1] "Add soft glow on image$?, with amplitude $1."
  -v - -repeat @#
    --b[-1] $1 -n[-1] [-2] -compose_edges[-2,-1] 1
  -mv[-1] 0 -done -v +

#@gmic hardsketchbw : _amplitude>=0,_density>=0,_opacity,0<=_edge_threshold<=100,_is_fast={ 0 | 1 }
#@gmic : Apply hard B&W sketch effect on selected images.
#@gmic : Default values : 'amplitude=1000', 'sampling=3', 'opacity=0.1', 'edge_threshold=20' and 'is_fast=0'.
#@gmic : $ image.jpg --hardsketchbw 200,70,0.1,10 -median[-1] 2 --local -reverse -blur[-1] 3 -compose_overlay -endl
hardsketchbw : -skip ${1=300},${2=50},${3=0.1},${4=20},${5=0}
  -e[^-1] "Apply hard B&W sketch effect on image$?, with amplitude $1, density $2, opacity $3 and edge threshold $4."
  -if {!$2} -channels 0 -f 255 -return -endif
  -v - -luminance -n 0,1

  -if $5 # Fast version.
    -repeat @#
      -g[-1] xy -rv[-2,-1] -*[-2] -1 -a[-2,-1] c
      -if $4 --norm[-1] -t[-1] $4% -*[-2,-1] -endif
      100%,100%,1,1,255 -quiver[-1] [-2],{max(1,10-$2/6)},$1,0,$3 -rm[-2]
    -mv[-1] 0 -done

  -else # Slow version.
    -repeat @#

      # Isolate starting points and tangents.
      w={w} h={h} -g[-1] xy -rv[-2,-1] -*[-2] -1 -a[-2,-1] c -*[-1] $1
      --norm[-1] -t[-1] $4% 100%,100% -noise[-1] $2,2 -*[-2,-1]

      # Retrieve points coordinates and corresponding tangents.
      -pointcloud3d[-1] -s3d[-1] -rm[-6--5,-3--1] -r[-1] 3,{h/3},1,1,-1 -s[-1] x -rm[-1] -a[-2,-1] c
      -warp[-2] [-1],0,0 ---[-1] [-2] -+[-3,-2] -s[-2,-1] c

      # Convert as a 3d object and render on white background.
      -i[-3] 1,{h} 1,{h} -a[-6--1] x
      -i[-2] ({'CImg3d'}) -i[-2] ({2*h},{h})
      1,{h},1,1,2 1,{h},1,1,2*y --+[-1] 1 -a[-3--1] x
      3,{h} 1,{h},1,1,$3 -y[-6--1] y -a[-6--1] y
      $w,$h,1,1,255 mode=@* -m3d 1 -object3d[-1] [-2],0,0,0,1,0 -rm[-2] -m3d $mode
    -mv[-1] 0 -done
  -endif -v +

#@gmic hearts : _density>=0
#@gmic : Apply heart effect on selected images.
#@gmic : Default value : 'density=10'.
#@gmic : $ image.jpg --hearts ,
hearts : -skip ${1=10}
  -e[^-1] "Apply heart filter on image$?, with density $1."
  -v - -repeat @#
    100%,100%,1 -noise[-1] $1,2 -r[-1] [-2] -n[-1] 0,1 -*[-1,-2] -_heart9x7
    -mirror[-1] y -dilate[-2] [-1] -rm[-1]
  -mv[-1] 0 -done -v +

_heart9x7 :
  (0,1,1,0,0,0,1,1,0;1,1,1,1,0,1,1,1,1;1,1,1,1,1,1,1,1,1;0,1,1,1,1,1,1,1,0;0,0,1,1,1,1,1,0,0;0,0,0,1,1,1,0,0,0;0,0,0,0,1,0,0,0,0)

#@gmic houghsketchbw : _density>=0,_radius>0,0<=_threshold<=100,0<=_opacity<=1,_votesize[%]>0
#@gmic : Apply hough B&W sketch effect on selected images.
#@gmic : Default values : 'density=8', 'radius=5', 'threshold=80', 'opacity=0.1' and 'votesize=100%'.
#@gmic : $ image.jpg --houghsketchbw ,
houghsketchbw : -check "${1=8}>=0 && ${2=5}>=0 && ${3=80}>=0 && $3<=100 && ${4=0.1}>=0 && $4<=1 && ${5=100%}>0"
  -e[^-1] "Apply hough B&W sketch effect on image$?, with density $1, radius $2, threshold $3, opacity $4 and votesize $5."
  -v - -repeat @#

    # Compute normalized Hough transform.
    res={round(if(@{"-is_percent $5"},$5*max(w,h),$5))} w={w} h={h} rhomax={sqrt(w^2+h^2)/2}
    -hough[-1] $res,$res -n[-1] 0,255

    # Retrieve coordinates of maximas in hough space.
    -normalize_local[-1] $1,$2 -t[-1] $3% -pointcloud3d[-1]
    -s3d[-1] -rm[-6--5,-3--1] -r[-1] 3,{h/3},1,1,-1 -columns[-1] 0,1

    # Convert to (x0,y0)-(x1,y1) line coordinates.
    -s[-1] x,2
    -*[-2] {2*pi/$res}                   # theta
    -*[-1] {$rhomax/$res}                # rho
    --cos[-2] -*[-1] [-2] -+[-1] {$w/2}  # x
    --sin[-3] -*[-1] [-3] -+[-1] {$h/2}  # y
    -rm[-3]                              # Remove rho
    -i[-3] [-3]
    -cos[-4] -sin[-3] -*[-4,-3] 10000    # cos(t) sin(t)
    --+[-2] [-3]                         # x + sin(t)
    ---[-2] [-5]                         # y - cos(t)
    --[-4] [-5]                          # x - sin(t)
    -+[-3] [-6]                          # y + cos(t)
    -rm[-6,-5]

    # Transform as a 3d object.
    -i[-3] 1,{h} 1,{h} -a[-6--1] x                  # Vertices
    -i[-2] ({'CImg3d'}) -i[-2] ({2*h},{h})          # Header and size.
    1,{h},1,1,2 1,{h},1,1,2*y --+[-1] 1 -a[-3--1] x # Primitives.
    3,{h},1,1,0 1,{h},1,1,$4                        # Colors and opacities
    -y[-6--1] y -a[-6--1] y

    # Render on a white image.
    $w,$h,1,1,255 mode=@* -m3d 1 -object3d[-1] [-2],0,0,0,1,0 -rm[-2] -m3d $mode
  -mv[-1] 0 -done -v +

#@gmic lightrays : 100<=_density<=0,_cx,_cy,_ray_length>=0,_ray_attenuation>=0
#@gmic : Generate ray lights from the edges of selected images.
#@gmic : Defaults values : 'density=50%', 'cx=0.5', 'cy=0.5', 'ray_length=0.9' and 'ray_attenuation=0.5'.
#@gmic : $ image.jpg --lightrays , -+ -c 0,255
lightrays : -check "${1=50}>=0 && $1<=100 && ${4=1} && ${5=1}>=0" -skip ${2=0.5},${3=0.5}
  -e[^-1] "Generate ray lights from image$?, with density $1, center ($2,$3), ray length $4 and attenuation $5."
  -v - -repeat @#
    -gradient_norm[-1] -*[-1] -1 -lt $1% -euclidean2polar[-1] $2,$3
    -repeat {log(w)/log(2)} --shift[-1] {2^$>} -+[-2,-1] -done
    -function1d 0.5,0,1,{$4*w},1,{1+($4+1-$5)*w},0 -r[-1] @{-2,w},1,1,1,0
    (1,{w}) -r[-1] @{-2,w},1,1,1,3 -/[-2,-1]
    -r[-1] [-2] -*[-2,-1] -polar2euclidean[-1] $2,$3 -n[-1] 0,255
  -mv[-1] 0 -done -v +

#@gmic light_relief : _ambient_light,_specular_light,_specular_size,_darkness,_xl,_yl,_zl,_zscale,_opacity_bumpmap={ 0 | 1 }
#@gmic : Apply relief light to selected images.
#@gmic : Default values(s) : 'ambient_light=0.3', 'specular_light=0.5', 'specular_size=0.2', 'darkness=0', 'xl=0.2', 'yl=zl=0.5',
#@gmic : 'zscale=1', 'opacity=1' and 'opacity_bumpmap=0'.
#@gmic : $ image.jpg --blur 2 -light_relief[-1] 0.3,4,0.1,0
light_relief : -skip ${1=0.3},${2=0.5},${3=0.2},${4=0},${5=0.2},${6=0.5},${7=0.5},${8=1},${9=1},${10=0}
  -e[^-1] "Apply relief light to image$?."
  -v - -repeat @#
    ({-$6},{1-$6};{-$6},{1-$6}^{-$7},{-$7};{1-$7},{1-$7}^$8,$8;$8,$8) -r[-1] [-2],[-2],1,3,3  # Create light vector field.
    -if $10 --channels[-2] 3 -to_rgb[-3] -else --to_rgb[-2] -norm[-1] -endif
    -b[-1] $5% -g[-1] xy 100%,100%,1,1,$9  -a[-3--1] c                                        # Create normal vector field.
    -orientation[-2,-1] -*[-2,-1] -s[-1] c -+[-3--1]                                          # Normalized scalar product.
    100%,100% -=[-1] 1,{$6*100}%,{$7*100}% -distance[-1] 1 -sqr[-1] -*[-1] -1                 # Compute specular attenuation.
    -/[-1] {($3*max(w,h))^2} -exp[-1] -*[-1] $2 -+[-1] $1
    -*[-2,-1] --[-1] $4 -*[-1] @{-2,M}
    -l[-2,-1] -split_opacity -rv[0--2]                                                        # Add light property to non-opaque part of the image.
    -+[-2,-1] -c[-1] 0,255
    -rv -a c -endl
  -mv[-1] 0 -done -v +

#@gmic mosaic : _density>=0,_edges={ 0 | 1 }
#@gmic : Create random mosaic from selected images.
#@gmic : Default values : 'density=0.8' and 'edges=1'.
#@gmic : $ image.jpg --mosaic ,
mosaic : -skip ${1=0.8},${2=1}
  -e[^-1] "Apply mosaic effect on image$?, with density $1."
  -v - -repeat @#
    label0={1+@{-1,m}} -+[-1] $label0
    100%,100% -noise[-1] {$1*2},2 -*[-2] [-1] -distance[-1] 1 -*[-1] -1 -watershed[-2] [-1],{if($2,0,1)} -rm[-1]
    -if $2 --l[-1] -t 0.0001 -s c -and -endl --[-2] $label0 -*[-2,-1] -else --[-1] $label0 -endif
  -mv[-1] 0 -done -v +

#@gmic old_photo
#@gmic : Apply old photo effect on selected images.
#@gmic : $ image.jpg --old_photo
old_photo :
  -e[^-1] "Apply old photo effect on image$?."
  -v - -noise 20 -bilateral 30,60 -b 2 -sharpen 100 -frame_fuzzy 20,20,6,3 -shadow_patch 0.75 -n 0,255 -sepia -v +

#@gmic pencilbw : _size>=0,_amplitude>=0
#@gmic : Apply B&W pencil effect on selected images.
#@gmic : Default values : 'size=0.3' and 'amplitude=60'.
#@gmic : $ image.jpg --pencilbw ,
pencilbw : -skip ${1=0.3},${2=60}
  -e[^-1] "Apply B&W pencil effect on image$?, with size $1 and amplitude $2."
  -v - -repeat @#
    -to_rgb[-1] -norm[-1] -b[-1] $1 -sharpen[-1] 4000 -smooth[-1] $2,0,1 -equalize[-1] 256 -sqrt[-1] -n[-1] 0,255
  -mv[-1] 0 -done -v +

#@gmic polaroid : _size1>=0,_size2>=0
#@gmic : Create polaroid effect in selected images.
#@gmic : Defaut values : 'size1=10' and 'size2=20'.
#@gmic : $ image.jpg -to_rgba -polaroid 5,30 -rotate 20 -drop_shadow , -display_rgba
polaroid : -check "${1=10}>=0 && ${2=20}>=0"
  -e[^-1] "Create polaroid effect in image$?, with borders sizes $1 and $2."
  -v - -- 255 -r {100+$1}%,{100+$1}%,1,100%,0,0,0.5,0.5 -r 100%,{100+$2}%,1,100%,0,0,0 -+ 255 -v +

#@gmic puzzle : _scale>=0
#@gmic : Apply puzzle effect on selected images.
#@gmic : Default value : 'scale=5'.
#@gmic : $ image.jpg --puzzle ,
puzzle : -skip ${1=5}
  -e[^-1] "Apply puzzle effect on image$?, with scale $1%."
  -v - -repeat @#
    [-1] -r[-1] $1%,$1%,100%,100%,2 -noise[-1] 0.1 -r[-1] [-2] -rm[-2]
    [-1]x2 -shift[-1] -1,-1 --[-2,-1] -norm[-1] -t[-1] 0.01 -*[-1] -1
    -+[-1] 1 -r[-1] [-2] -*[-1,-2] 10%,10%,10%,2 -noise[-1] 5,1
    -r[-1] [-2],[-2],1,2,5 -warp[-2] [-1],1,1,1 -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic rodilius : 0<=_amplitude<=100,_0<=thickness<=100,_sharpness>=0,_nb_orientations>0,_offset,_color_mode={ 0=darker | 1=brighter }
#@gmic : Apply rodilius (fractalius-like) filter on selected images.
#@gmic : Default values : 'amplitude=10', 'thickness=10', 'sharpness=400', 'nb_orientations=7', 'offset=0' and 'color_mode=1'.
#@gmic : $ image.jpg --rodilius 12,10,300,10 -normalize_local[-1] 10,6
rodilius : -check "${1=10}>=0 && $1<=200 && ${2=10}>=0 && $2<=100 && ${3=400}>=0 && ${4=7}>0" -skip ${5=0},${6=1}
  -e[^-1] "Apply rodilius filter on image$? with amplitude $1, thickness $2, sharpness $3, $4 orientations, offset $5 and "\
    @{"-if $6 -u brighter -else -u darker -endif"}" color mode."
  -v - -repeat @# -l[$>] -split_opacity -rv
    -if {!$6} -negative[-1] -endif
    --f[-1] 0
    -repeat {round($4)}
      angle={$5+$>*180/round($4)}
      --blur_linear[-2] $1%,{$1*$2/100}%,$angle,1 -b[-1] 0.7 -sharpen[-1] $3 -max[-2,-1]
    -done -rm[-2]
    -if {!$6} -negative[-1] -endif
  -rv -a c -endl -done -v +

#@gmic stained_glass : _edges[%]>=0, shading>=0, is_thin_separators={ 0 | 1 }
#@gmic : Generate stained glass from selected images.
#@gmic : Default values : 'edges=40%', 'shading=0.2' and 'is_precise=0'.
#@gmic : $ image.jpg --stained_glass ,
stained_glass : -check "${1=40%}>=0 && ${2=0.2}>=0" -skip ${3=0}
  -e[^-1] "Apply stained glass effect on image$?, with edges $1, shading $2 and thin-separators "@{"-if $3 -u enabled -else -u disabled -endif"}"."
  -v - -repeat @#
    im={1+im} -+[-1] $im  # Ensure positiveness of image labels.
    --gradient_norm[-1] -t[-1] $1 -*[-2] [-1]
    -distance[-1] 1 -sharpen[-1] 1e10 -neq[-1] 0
    -if $3 -skeleton[-1] 0 -endif
    -distance[-1] 1 -watershed[-2] [-1] --[-2] $im
    -n[-1] 0,1  -^[-1] $2 -*[-2,-1]
  -mv[-1] 0 -done -v +

#@gmic sketchbw
#@gmic : _nb_orients>0,_start_angle,_angle_range>=0,_length>=0,_threshold>=0,
#@gmic : _opacity,_bgfactor>=0,_density>0,_sharpness>=0,
#@gmic : _anisotropy>=0,_smoothness>=0,_coherence>=0,_is_boost={ 0 | 1 },_is_curved={ 0 | 1 }\n
#@gmic : Apply sketch effect to selected images.
#@gmic : Default values : 'nb_orients=2', 'start_angle=45', 'angle_range=180', 'length=30', 'threshold=1', 'opacity=0.03',
#@gmic : 'bgfactor=0', 'density=0.6', 'sharpness=0.1', 'anisotropy=0.6', 'smoothness=0.25', 'coherence=1', 'is_boost=0' and 'is_curved=1'.
#@gmic : $ image.jpg --sketchbw 1 --local -reverse -blur[-1] 3 -compose_overlay -endl
sketchbw :
  -check "${1=2}>0 && ${3=180}>=0 && ${4=30}>=0 && ${5=1}>=0 && ${7=0}>=0 && ${8=0.6}>0 && ${9=0.1}>=0 && ${10=0.6}>=0 && ${11=0.25}>=0 && ${12=1}>=0"
  -skip ${2=45},${6=0.03},${13=0},${14=1}
  -e[^-1] "Apply B&W sketch effect on image$?."
  -v - -diffusiontensors $9,$10,$11,$12
  w=1 h=1 -i[0] 1 mode=@* -m3d 0

  -repeat {@#-1}
    -/[-1] {max(iM,im)} -s[-1] c     # Normalize and split tensor coefficients.
    100%,100%,1,1,255                # Create rendering B&W image.

    -if {$w!=w||$h!=h}               # Create set of random coordinates, if necessary.
      -rm[0] {$8*w*h/($1*sqrt($4))}
      --rand[-1] 0,{@{-2,h}-1} -rand[-2] 0,{@{-3,w}-1} -a[-2,-1] y -mv[-1] 0
      w={w} h={h}
    -endif

    -if $14 # Render sketch with curved strokes
      -repeat $1
        alpha={($2+$>*$3/$1)*pi/180}
        --*[-4] {cos($alpha)} --*[-4] {sin($alpha)} -+[-2,-1]
        --*[-4] {cos($alpha)} --*[-4] {sin($alpha)} -+[-2,-1]
        -a[-2,-1] c -channels[-1] 0,2
        -if $13 -orientation[-1] -endif
        -repeat @{0,w}
          xy=@{0,($>,0)},@{0,($>,1)}
          -if {@{-5,($xy)}+@{-3,($xy)}<$5} opac=$6 -else opac={$7*$6} -endif
          -if $opac
            --streamline3d[-1] $xy,0,$4,0.8,0,0,1 -col3d[-1] 0,0,0 -object3d[-3] [-1],0,0,0,$opac,0 -rm[-1]
            --streamline3d[-1] $xy,0,$4,0.8,0,1,1 -col3d[-1] 0,0,0 -object3d[-3] [-1],0,0,0,$opac,0 -rm[-1]
          -endif
        -done
        -rm[-1]
      -done

    -else # Render sketch with straight strokes
      -repeat $1
        alpha={($2+$>*$3/$1)*pi/180}
        --*[-4] {cos($alpha)} --*[-4] {sin($alpha)} -+[-2,-1]
        --*[-4] {cos($alpha)} --*[-4] {sin($alpha)} -+[-2,-1]
        -a[-2,-1] c
        -if $13 -orientation[-1] -endif
        -repeat @{0,w}
          x=@{0,($>,0)} y=@{0,($>,1)}
          -if {@{-5,($x,$y)}+@{-3,($x,$y)}<$5} opac=$6 -else opac={$7*$6} -endif
          -if $opac
            -line[-2] {$x-$4*@{-1,($x,$y,0,0)}},{$y-$4*@{-1,($x,$y,0,1)}},\
                      {$x+$4*@{-1,($x,$y,0,0)}},{$y+$4*@{-1,($x,$y,0,1)}},\
                      {3*$opac},0
          -endif
        -done
        -rm[-1]
      -done

    -endif
    -rm[-4--2]
  -mv[-1] 1 -done -rm[0] -m3d $mode -v +

#@gmic sponge : _size>0
#@gmic : Apply sponge effect on selected images.
#@gmic : Default value : 'size=13'.
#@gmic : $ image.jpg --sponge ,
sponge : -skip ${1=13}
  -e[^-1] "Apply sponge filter on image$?, with brush size $1."
  -v - -repeat @#
    100%,100%,1,1 -noise[-1] 20,2 -r[-1] [-2] -n[-1] 0,1 -*[-1,-2]
    -_circle $1 -dilate[-2] [-1] -rm[-1]
  -mv[-1] 0 -done -v +

_circle :
  -if {$1%2==0} -i 2,2 -else -i 1 -endif
  -+[-1] 1 -r[-1] $1,$1,1,1,0,0,0.5,0.5 -distance[-1] 1 -n[-1] 0,1 -sqrt[-1] -c[-1] 0.85,0.86 -*[-1] -1 -n[-1] 0,1

#@gmic stencil : _radius[%]>=0,_smoothness>=0,_iterations>=0
#@gmic : Apply stencil filter on selected images.
#@gmic : Default values : 'radius=3', 'smoothness=1' and 'iterations=8'.
#@gmic : $ image.jpg --stencil 1,10,3
stencil : -check "${1=3}>=0 && ${2=1}>=0 && ${3=8}>=0"
  -e[^-1] "Apply stencil filter on image$?, with radius $1, smoothness $2 and $3 iterations."
  -v -
  -n 0,1 -repeat $3 -b $1 -unsharp {$1+$2},1000 -c 0,255 -done
  -v +

#@gmic stencilbw : _edges>=0,_smoothness>=0
#@gmic : Apply B&W stencil effect on selected images.
#@gmic : Default values : 'edges=15' and 'smoothness=10'.
#@gmic : $ image.jpg --stencilbw 40,4
stencilbw : -skip ${1=15},${2=10}
  -e[^-1] "Apply B&W stencil effect on image$?, with edges $1 and smoothness $2."
  -v - -repeat @#
    -r[-1] 100%,100%,1,100% --edges[-1] $1 -quantize[-2] 3 -b[-2] $2
    -sharpen[-2] 1000000 -norm[-2] -n[-2] 0,1 -*[-1,-2] -n[-1] 0,255
  -mv[-1] 0 -done -v +

#@gmic tetris : _scale>0
#@gmic : Apply tetris effect on selected images.
#@gmic : Default value : 'scale=10'.
#@gmic : $ image.jpg --tetris 10
tetris : -skip ${1=10}
  -e[^-1] "Apply tetris effect on image$?, with scale $1."
  -v - -repeat @#
    --r[-1] $1%,$1%,$1%,3,2 -n[-1] 0,255 -quantize[-1] 10
    -r[-1] [-2] -rm[-2] -b[-1] 2 -sharpen[-1] 300,1
  -mv[-1] 0 -done -v +

#@gmic warhol : _M>0,_N>0,_smoothness>=0,_color>=0
#@gmic : Create MxN Andy Warhol-like artwork from selected images.
#@gmic : Default values : 'M=3', 'N=M', 'smoothness=2' and 'color=20'.
#@gmic : $ image.jpg --warhol 5,3,3,40
warhol : -skip ${1=3},${2=$1},${3=2},${4=20}
  -e[^-1] "Create $1x$2 Andy Warhol-like artwork from image$?."
  -v - -repeat @#
    -norm[-1] -b[-1] $3 -array_expand0 $1,$2 -quantize[-1] 6 -n[-1] 0,5 -round[-1] 1
    -l[-1] -repeat $1 -repeat $2
      (0,1,2,3,4,5) -n[-1] 32,224 6,1,1,2,128 -noise[-1] $4,0 -c[-1] 0,255 -a[-2,-1] c -ycbcr2rgb[-1] --map[0] [-1] -rm[-2]
    -done -done -append_tiles[1--1] $1,$2 -rm[0] -endl
  -mv[-1] 0 -done -v +

#@gmic whirls : _texture>=0,_smoothness>=0,_darkness>=0,_lightness>=0
#@gmic : Add random whirl texture to selected images.
#@gmic : Default values : 'texture=3', 'smoothness=6', 'darkness=0.5' and 'lightness=1.8'.
#@gmic : $ image.jpg --whirls ,
whirls : -skip ${1=3},${2=6},${3=0.5},${4=1.8}
  -e[^-1] "Add random whirl texture to image$?, with texture $1, smoothness $2, darkness $3 and lightness $4."
  -v - -repeat @#
    100%,100% -noise[-1] 0.3,2 -repeat $1 -b[-1] $2 -gradient_norm[-1] -^[-1] 0.2 -done
    -n[-1] $3,$4 -r[-1] [-2] -*[-2,-1] -c[-1] 0,255
  -mv[-1] 0 -done -v +

#------------------------------------
#
#@gmic :: Warpings
#
#------------------------------------

#@gmic euclidean2polar : _cx,_cy,_n>0,_boundary={ 0=dirichlet | 1=neumann | 2=cyclic }
#@gmic : Apply euclidean to polar transform on selected images.
#@gmic : Default values : 'cx=cy=0.5', 'n=1' and 'boundary=1'.
#@gmic : $ image.jpg --euclidean2polar ,
euclidean2polar : -skip ${1=0.5},${2=0.5},${3=1},${4=1}
  -e[^-1] "Apply euclidean to polar transform on image$?."
  -v - -repeat @#
    ({w},{h}) ($1,$2) -*[-2,-1] ({"sqrt(max("@{-1,0}","@{-2,w}"-"@{-1,0}")^2 + max("@{-1,1}","@{-2,h}"-"@{-1,1}")^2)"})
    -a[-2,-1] x
    [-2],[-2],1,1,@{-1,2}"*(x/w)^$3*cos(y*2*pi/h)" -+[-1] @{-2,0}
    [-1],[-1],1,1,@{-2,2}"*(x/w)^$3*sin(y*2*pi/h)" -+[-1] @{-3,1}
    -rm[-3] -a[-2,-1] c -warp[-2] [-1],0,1,$4 -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic deform : _amplitude>=0
#@gmic : Apply random smooth deformation on selected images.
#@gmic : Default value : 'amplitude=10'.
#@gmic : $ image.jpg --deform[0] 10 --deform[0] 20
deform : -skip ${1=10}
  -e[^-1] "Apply random smooth deformation on image$?, with amplitude $1."
  -v - -repeat @#
    2%,2%,1,2 -noise[-1] $1 -r[-1] [-2],[-2],1,2,5 -warp[-2] [-1],1,1,1 -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic fisheye : _x,_y,0<=_radius<=100,_amplitude>=0
#@gmic : Apply fish-eye deformation on selected images.
#@gmic : Default values : 'x=y=50', 'radius=50' and 'amplitude=1.2'.
#@gmic : $ image.jpg --fisheye ,
fisheye : -skip ${1=50},${2=50},${3=50},${4=1.2}
  -if {$4==0} -return -endif
  -e[^-1] "Apply Fish-eye effect on image$?, centered at ($1%,$2%) with radius $3% and amplitude $4."
  -v - -repeat @#
    100%,100%,1,1 -=[-1] 1,$1%,$2% -distance[-1] 1 -c[-1] 0,$3% -*[-1] -1 -n[-1] 0,1 -^[-1] {1/$4}
    -i[-2] ({-$1/100},{1-$1/100};{-$1/100},{1-$1/100}^{-$2/100},{-$2/100};{1-$2/100},{1-$2/100}) -r[-2] [-1],[-1],1,2,3
    -n[-1] 0,{max(w,h)} -*[-2,-1]
    -warp[-2] [-1],1,1,1 -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic flower : _amplitude,_frequency,_offset_r[%],_angle,_cx,_cy,_boundary={ 0=dirichlet | 1=neumann | 2=cyclic }
#@gmic : Apply flower deformation on selected images.
#@gmic : Default values : 'amplitude=30', 'frequency=6', 'offset_r=0', 'angle=0', 'cx=cy=0.5' and 'boundary=2'.
#@gmic : $ image.jpg -flower ,
flower : -skip ${1=30},${2=6},${3=0},${4=0},${5=0.5},${6=0.5},${7=2}
  -e[^-1] "Apply flower deformation on image$?, with amplitude $1, frequency $2, offset $3, angle $4° and center ($1,$2)."
  -v - -repeat @#
    -euclidean2polar[-1] $5,$6,1,$7 -shift[-1] $3,0,0,0,2
    100%,100%,1,1,y -/[-1] {h} -*[-1] $2 ({$4/360}) -+[-2] @-1 -rm[-1] -*[-1] 6.2831853 -sin[-1]
    -*[-1] $1 -*[-1] {w} -/[-1] 100
    -channels[-1] 0,1 -warp[-2] [-1],1,1,$7 -rm[-1]
    -polar2euclidean[-1] $5,$6,1,1
  -mv[-1] 0 -done -v +

#@gmic kaleidoscope : _cx,_cy,_radius,_angle,_boundary={ 0=dirichlet | 1=neumann | 2=cyclic }
#@gmic : Create kaleidoscope effect from selected images.
#@gmic : Default values : 'cx=cy=0.5', 'radius=100', 'angle=30' and 'boundary=1'.
#@gmic : $ image.jpg --kaleidoscope ,
kaleidoscope : -skip ${1=0.5},${2=0.5},${3=100},${4=30},${5=1}
  -e[^-1] "Create kaleidoscope effect from image$?, with center ($1,$2), radius $3, angle $4°."
  -v - -euclidean2polar $1,$2,1,$5 -repeat @#
    --columns[-1] 0,$3% -lines[-1] 0,$4% -r[-1] [-2],0,2 -rm[-2]
  -mv[-1] 0 -done -polar2euclidean $1,$2,1,$5 -v +

#@gmic map_sphere : _width>0,_height>0,_radius,_dilation>0,_fading>=0,_fading_power>=0
#@gmic : Map selected images on a sphere.
#@gmic : Default values : 'width=height=512', 'radius=100', 'dilation=0.5', 'fading=0' and 'fading_power=0.5'.
#@gmic : $ image.jpg --map_sphere ,
map_sphere : -check "${1=512}>0 && ${2=512}>0 && ${5=0}>=0 && ${6=0.5}>=0" -skip ${3=100},${4=0.5}
   -e[^-1] "Map image$? on spheres in $1x$2 images, with radius $3, dilation $4 and fading $5."
   -v -
   r2={($3*min($1,$2)/200)^2} # Compute squared radius.
   -repeat @#
     -i[-2] 100%,1,1,100%,0 -a[-2,-1] y # Add one border line to have a sphere exterior.
     ({-$1/2},{$1/2}) ({-$2/2};{$2/2}) -r[-2,-1] $1,$2,1,1,3 -atan2[-1] [-2] -rm[-2] # Compute theta angle.
     $1,$2 -=[-1] 1,50%,50% -distance[-1] 1,3 -/[-1] $r2 -sqrt[-1] -c[-1] 0,1
     -asin[-1] # Compute phi angle.
     -+[-2] {pi} -*[-2] {(@{-3,w}-1)/(2*pi)} # Normalize theta to X-coordinates
     -*[-1] {2/pi} -^[-1] $4 -*[-1] {@{-3,h}-1} -*[-1] -1 -+[-1] {@{-3,h}-1} # Normalize phi to Y-coordinates
     -if $5 --ge[-1] 1 -distance[-1] 1 -c[-1] 0,$5% -n[-1] 0,1 -^[-1] $6 -c[-2] 1,100% --[-2,-1] -endif
     -a[-2,-1] c -warp[-2] [-1],0,1,1 -rm[-1] # Apply image warping
   -mv[-1] 0 -done -v +

#@gmic polar2euclidean : _cx,_cy,_n>0,_boundary={ 0=dirichlet | 1=neumann | 2=cyclic }
#@gmic : Apply polar to euclidean transform on selected images.
#@gmic : Default values : 'cx=cy=0.5', 'n=1' and 'boundary=1'.
#@gmic : $ image.jpg --euclidean2polar , -mirror[-1] x -polar2euclidean[-1] ,
polar2euclidean : -skip ${1=0.5},${2=0.5},${3=1},${4=1}
  -e[^-1] "Apply polar to euclidean transform on image$?."
  -v - -repeat @#
    ({w},{h}) ($1,$2) -*[-2,-1] ({"sqrt(max("@{-1,0}","@{-2,w}"-"@{-1,0}")^2 + max("@{-1,1}","@{-2,h}"-"@{-1,1}")^2)"})
    -a[-2,-1] x
    [-2],[-2],1,1,"w*(sqrt((x-"@{-1,0}")^2 + (y-"@{-1,1}")^2)/"@{-1,2}")^(1/$3)"
    [-1],[-1],1,1,"(atan2(y-"@{-2,1}",x-"@{-2,0}")*h/(2*pi)+h)%h"
    -rm[-3] -a[-2,-1] c -warp[-2] [-1],0,1,$4 -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic ripple : _amplitude,_frequency,_shape={ 0=bloc | 1=triangle | 2=sine | 3=sine+ | 4=random },_angle,_offset
#@gmic : Apply ripple deformation on selected images.
#@gmic : Default values : 'amplitude=10', 'frequency=10', 'shape=2', 'angle=0' and 'offset=0'.
#@gmic : $ image.jpg --ripple ,
ripple : -skip ${1=10},${2=20},${3=2},${4=0},${5=0}
  -e[^-1] "Apply ripple deformation on image$?, with amplitude $1, frequency $2, shape $3, angle $4° and offset $5."
  -v -
  theta={$4*pi/180} C={cos($theta)} S={-sin($theta)}
  -repeat @#
    100%,100%,1,1,"x" --[-1] {w/2} 100%,100%,1,1,'y'
    --[-1] {h/2-$5} -*[-2] $S -*[-1] $C -+[-2,-1]      # Generate rotated Y.
    -_ripple$3[-1] $1,$2                               # Generate warp field.
    --*[-1] {-$S} -*[-2] $C -a[-2,-1] c                # Rotate warp field.
    -warp[-2] [-1],1 -rm[-1]
  -mv[-1] 0 -done -v +

_ripple0 : -f {$1/2}*"(1-2*(i%"{2*$2}"<$2))"
_ripple1 : -f "I=(i%$2)/$2;$1*(2*if(I<0.5,I,1-I)-0.5)"
_ripple2 : -f {-$1/2}*"cos(i*"{2*pi/$2}")"
_ripple3 : -f {-$1/2}*"abs(cos(i*"{2*pi/$2}"))"
_ripple4 : -skip $* -n 0,{h-1} 1,{h} -rand[-1] {-$1/2},{$1/2} m={im} M={iM} -b[-1] {$2/10} -n[-1] $m,$M -map[-2] [-1] -rm[-1]

#@gmic rotoidoscope : _cx,_cy,_tiles>0,_smoothness[%]>=0,_boundary={ 0=dirichlet | 1=neumann | 2=cyclic}
#@gmic : Create rotational kaleidoscope effect from selected images.
#@gmic : Default values : 'cx=cy=50%', 'tiles=10', 'smoothness=1' and 'boundary=1'.
#@gmic : $ image.jpg --rotoidoscope ,
rotoidoscope : -skip ${1=50%},${2=50%},${5=1} -check "${3=10}>0 && ${4=1}>=0"
  -e[^-1] "Create rotational kaleidoscope effect from image$?, with center ($1,$2), $3 tiles and smoothness $4."
  -v - -repeat @# -l[-1]
    -repeat $3 --rotate[0] {360/$3},$5,1,$1,$2 -compose_edges $4 -done
  -endl -mv[-1] 0 -done -v +

#@gmic transform_polar : "expr_radius",_"expr_angle",_x_center,_y_center,_boundary={ 0=dirichlet | 1=neumann }
#@gmic : Apply user-defined transform on polar representation of selected images.
#@gmic : Default values : 'expr_radius=R-r', 'expr_rangle=a', 'x_center=y_center=50' and 'boundary=1'.
#@gmic : $ image.jpg --transform_polar[0] R*(r/R)^2,a --transform_polar[0] r,2*a
transform_polar : -skip "${1=R-r}","${2=a}",${3=50},${4=50},${5=1}
  -e[^-1] "Apply custom polar transform with 'new_r = $1', 'new_a = $2', centered at ($3%,$4%)."
  -v -
  -repeat @#
  R={"sqrt((max($3,100-$3)*w/100)^2 + (max($4,100-$4)*h/100)^2)"}
  w={"$3*w/100"}
  h={"$4*h/100"}
  -f "R ="$R";
      r = sqrt((x-"$w")^2 + (y-"$h")^2);
      a = atan2(y-"$h",x-"$w");
      nr = $1;
      na = $2;
      i("$w" + nr*cos(na), "$h" + nr*sin(na), z, c, 1,$5)"
  -mv[-1] 0 -done -v +

#@gmic twirl : _amplitude,_cx,_cy,_boundary={ 0=dirichlet | 1=neumann | 2=cyclic }
#@gmic : Apply twirl deformation on selected images.
#@gmic : Default values : 'amplitude=1', 'cx=cy=0.5' and 'boundary=1'.
#@gmic : $ image.jpg --twirl 0.6
twirl : -skip ${1=1},${2=0.5},${3=0.5},${4=1}
  -e[^-1] "Apply twirl deformation on image$?, with amplitude $1 and center at ($2%,$3%)."
  -v - -repeat @#
    -euclidean2polar[-1] $2,$3,1,$4 100%,100%,1,1,$1*x -channels[-1] -1,0
    -warp[-2] [-1],1,1,2 -rm[-1] -polar2euclidean[-1] $2,$3,1,1
  -mv[-1] 0 -done -v +

#@gmic warp_perspective : _x-angle,_y-angle,_zoom>0,_x-center,_y-center,_boundary={ 0=dirichlet | 1=neumann | 2=cyclic }
#@gmic : Warp selected images with perspective deformation.
#@gmic : Default values : 'x-angle=1.5', 'y-angle=0', 'zoom=1', 'x-center=y-center=50' and 'boundary=2'.
#@gmic : $ image.jpg --warp_perspective ,
warp_perspective : -skip ${1=1.5},${2=0},${3=1},${4=50},${5=50},${6=2}
  -e[^-1] "Apply perspective warp on image$?, with angles ($1°,$2°), zoom $3 and offsets ($4,$5)."
  -v - -repeat @#
    (0,100) --[-1] $4 -/[-1] 100 (0;100) --[-1] $5 -/[-1] 100 -r[-2,-1] [-3],[-3],[-3],1,3
    --*[-2] $2 --*[-2] $1 -+[-2,-1] -+[-1] $3 -/[-3] [-1] -/[-2,-1]
    -*[-2] 100 -+[-2] $4 -/[-2] 100 -*[-2] @{-3,w}
    -*[-1] 100 -+[-1] $5 -/[-1] 100 -*[-1] @{-3,h}
    -a[-2,-1] c -warp[-2] [-1],0,1,$6 -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic water : _amplitude>=0,_smoothness>=0
#@gmic : Apply water deformation on selected images.
#@gmic : Default values : 'amplitude=30' and 'smoothness=1.5'.
#@gmic : $ image.jpg --water ,
water : -skip ${1=30},${2=1.5}
  -e[^-1] "Apply water deformation on image$?, with amplitude $1 and smoothness $2."
  -v - -repeat @#
    25%,25%,25%,1 -noise[-1] $1 -g[-1] xyz -+[-1,-2,-3] -b[-1] $2 -*[-1] 2 -r[-1] [-2],[-2],1,2,3 -warp[-2] [-1],1 -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic wave : _amplitude>=0,_frequency>=0,_center_x,_center_y
#@gmic : Apply wave deformation on selected images.
#@gmic : Default values : 'amplitude=4', 'frequency=0.4' and 'center_x=center_y=50'.
#@gmic : $ image.jpg --wave ,
wave : -skip ${1=4},${2=0.4},${3=50},${4=50}
  -e[^-1] "Apply wave deformation on image$?, with amplitude $1, frequency $2 and center at ($3%,$4%)."
  -v - -repeat @#
    100%,100% -=[-1] 1,$3%,$4% -distance[-1] 1
    -*[-1] $2 --sin[-1] -cos[-2] -a[-2,-1] c -*[-1] $1
    -warp[-2] [-1],1 -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic wind : _amplitude>=0,_angle,0<=_attenuation<=1,_threshold
#@gmic : Apply wind effect on selected images.
#@gmic : Default values : 'amplitude=20', 'angle=0', 'attenuation=0.7' and 'threshold=20'.
#@gmic : $ image.jpg --wind ,
wind : -check "isint(${1=20}) && $1>=0 && ${3=0.7}>=0 && $3<=1" -skip "${2=0},${4=20}"
  -e[^-1] "Apply wind effect on image$?, with amplitude $1, angle "{round($2/45)*45}" deg., attenuation $3 and threshold $4."
  -v -
  -if {!$1} -return -endif
  dxdy=@{-_wind{round($2/45)%8}}
  fact={(1-$3)^(1/$1)}
  -repeat @# -l[$>]
    --gradient_norm -t[-1] $4%
    sum=@{-1,+} -r[-1] 100%,100%,1,[-2] -*[-1] [-2]
    -repeat $1
      -shift[-1] $dxdy,0,0,0 -max[-2] [-1] -*[-1] $fact
      -remove_pixels[-1] {100/$1},$sum
    -done -rm[-1]
  -endl -done -v +

_wind0 : -u 1,0
_wind1 : -u 1,1
_wind2 : -u 0,1
_wind3 : -u -1,1
_wind4 : -u -1,0
_wind5 : -u -1,-1
_wind6 : -u 0,-1
_wind7 : -u 1,-1

#@gmic zoom : _factor,_cx,_cy,_cz,_boundary={ 0=dirichlet | 1=neumann | 2=cyclic }
#@gmic : Apply zoom factor to selected images.
#@gmic : Default values : 'factor=1', 'cx=cy=cz=0.5' and 'boundary=0'.
#@gmic : $ image.jpg --zoom[0] 0.6 --zoom[0] 1.5
zoom : -skip ${1=2},${2=0.5},${3=0.5},${4=0.5},${5=0}
  -e[^-1] "Apply zoom effect on image$?, with factor $1 and center ($2,$3)."
  -v - -repeat @#
    -if {d==1} # 2d image.
       ({(w-1)*$2*(1-1/$1)},{(w-1)*($2+(1-$2)/$1)})
       ({(@{-2,h}-1)*$3*(1-1/$1)};{(@{-2,h}-1)*($3+(1-$3)/$1)})
       -r[-2--1] [-3],[-3],1,1,3 -a[-2--1] c -warp[-2] [-1],0,1,$5
    -else # 3d image.
       ({(w-1)*$2*(1-1/$1)},{(w-1)*($2+(1-$2)/$1)})
       ({(@{-2,h}-1)*$3*(1-1/$1)};{(@{-2,h}-1)*($3+(1-$3)/$1)})
       ({(@{-3,d}-1)*$4*(1-1/$1)}/{(@{-3,d}-1)*($4+(1-$4)/$1)})
       -r[-3--1] [-4],[-4],[-4],1,3 -a[-3--1] c -warp[-2] [-1],0,1,$5
    -endif
    -rm[-1]
  -mv[-1] 0 -done -v +

#-----------------------------
#
#@gmic :: Degradations
#
#-----------------------------

#@gmic cracks : _density>=0,_amplitude,_relief={ 0 | 1 }
#@gmic : Add random cracks to selected images.
#@gmic : Default values : 'density=0.2', 'amplitude=40' and 'relief=0'.
#@gmic : $ image.jpg --cracks 0.2,60,1
cracks : -skip ${1=0.2},${2=40},${3=0}
  -e[^-1] "Add random cracks to image$?, with density $1."
  -v - -repeat @#
    (@{-1,m},@{-1,M}) [-2],[-2],1,1 -noise[-1] $1,2 -distance[-1] 1 -sharpen[-1] 10000
    -if $3 -g[-1] xy -+[-2,-1] -n[-1] -1,1 -else -n[-1] 0,1 -endif
    -*[-1] $2 -+[-3,-1] -c[-2] @-1 -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic light_patch : _density>0,_darkness>=0,_lightness>=0
#@gmic : Add light patches to selected images.
#@gmic : Default values : 'density=10', 'darkness=0.9' and 'lightness=1.7'.
#@gmic : $ image.jpg --light_patch 20,0.9,4
light_patch : -skip ${1=10},${2=0.9},${3=1.7}
  -e[^-1] "Apply light patches to image$?, with density $1, darkness $2 and lightness $3."
  -v - -repeat @#
    -n[-1] 0,255 $1,$1 -noise[-1] 40 -r[-1] [-2],5 -c[-1] 0,255
    -n[-1] $2,$3 -*[-2,-1] -c[-1] 0,255
  -mv[-1] 0 -done -v +

#@gmic noise_hurl : _amplitude>=0
#@gmic : Add hurl noise to selected images.
#@gmic : Default value : 'amplitude=10'.
#@gmic : $ image.jpg --noise_hurl ,
noise_hurl : -skip ${1=10}
  -e[^-1] "Add hurl noise to image$?, with amplitude $1%."
  -v - -repeat @#
    --f[-1] 0 -noise[-1] 10 -n[-1] @{-2,m},@{-2,M} 100%,100%,1,1,-2
    -noise[-1] $1,2 -t[-1] 0 -r[-1] [-2]
    -*[-2] [-1] -*[-1] -1 -+[-1] 1 -*[-3,-1] -+[-2,-1]
  -mv[-1] 0 -done -v +

#@gmic pixelize : _scale_x>0,_scale_y>0,_scale_z>0
#@gmic : Pixelize selected images with specified scales.
#@gmic : Default values : 'scale_x=20' and 'scale_y=scale_z=scale_x'.
#@gmic : $ image.jpg --pixelize ,
pixelize : -skip ${1=20},${2=$1},${3=$1}
  -e[^-1] "Pixelize image$? with scales ($1%,$2%,$3%)."
  -v - -repeat @#
    ({w},{h},{d}) -r[-2] $1%,$2%,$3%,[-2],2 -r[-2] @-1 -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic shade_stripes : _frequency>=0,_direction={ 0=horizontal | 1=vertical },_darkness>=0,_lightness>=0
#@gmic : Add shade stripes to selected images.
#@gmic : Default values : 'frequency=5', 'direction=1', 'darkness=0.8' and 'lightness=2'.
#@gmic : $ image.jpg --shade_stripes 30
shade_stripes : -skip ${1=5},${2=1},${3=0.8},${4=2}
  -v - -repeat @#
    -n[-1] 0,255
    -if $2 -v + -e[^-1] "Add vertical shaded stripes to image$?, with frequency $1, darkness $3 and lightness $4." -v - 100%
    -else -v + -e[^-1] "Add horizontal shaded stripes to image$?, with frequency $1, darkness $3 and lightness $4." -v - 1,100%
    -endif
    -noise[-1] $1,2 -distance[-1] 1
    -r[-1] [-2] -n[-1] $3,$4 -*[-1,-2] -c[-1] 0,255
  -mv[-1] 0 -done -v +

#@gmic shadow_patch : _opacity>=0
#@gmic : Add shadow patches to selected images.
#@gmic : Default value : 'opacity=0.7'.
#@gmic : $ image.jpg --shadow_patch 0.4
shadow_patch : -skip ${1=0.7}
  -e[^-1] "Apply shadow patches to image$?, with opacity $1."
  -v - -repeat @#
    100%,100%,1,1 -shift[-1] -2,-2 -shift[-1] 1,1
    -plasma[-1] 3,0.3,8 -abs[-1] -b[-1] 1 -c[-1] 3%,15% -r[-1] [-2]
    -n[-1] $1,1 -*[-1,-2]
  -mv[-1] 0 -done -v +

#@gmic spread : _dx>=0,_dy>=0,_dz>=0
#@gmic : Spread pixel values of selected images randomly along x,y and z.
#@gmic : Default values : 'dx=3', 'dy=dx' and 'dz=0'.
#@gmic : $ image.jpg --spread 3
spread : -skip ${1=3},${2=$1},${3=0}
  -e[^-1] "Spread pixel of image$? randomly, with amplitudes ($1,$2,$3)."
  -v - -repeat @#
    100%,100%,100%,1 [-1]x2 -noise[-3] $1,0 -noise[-2] $2,0 -noise[-1] $3,0 -a[-3--1] c -warp[-2] [-1],1 -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic stripes_y : _frequency>=0
#@gmic : Add vertical stripes to selected images.
#@gmic : Default value : 'frequency=10'.
#@gmic : $ image.jpg --stripes_y ,
stripes_y : -skip ${1=10}
  -e[^-1] "Add vertical stripes to image$?, with frequency $1."
  -v - -repeat @#
    -n[-1] 0,255 100% -noise[-1] $1,2 -*[-1] 255 -r[-1] [-2]
    -*[-1] 0.15 -+[-1,-2] -c[-1] 0,255
  -mv[-1] 0 -done -v +

#@gmic texturize_canvas : _amplitude>=0,_fibrousness>=0,_emboss_level>=0
#@gmic : Add paint canvas texture to selected images.
#@gmic : Default values : 'amplitude=20', 'fibrousness=3' and 'emboss_level=0.6'.
#@gmic : $ image.jpg --texturize_canvas ,
texturize_canvas : -check "${1=20}>=0 && ${2=3}>=0 && ${3=0.6}>=0 && ${4=80}"
  -e[^-1] "Add canvas texture to image$?, with amplitude $1, fibrousness $2 and emboss level $3."
  -repeat @#
    {w},{h} -rand[-1] 0,255 --blur_x[-1] $2 -blur_y[-2] $2 -+[-2,-1] -g[-1] -a[-2,-1] c
    --compose_channels[-1] + -orientation[-2] -compose_channels[-2] + -n[-2] $3,1 -n[-1] 0,255
    -sharpen[-1] 80 -*[-2,-1] -n[-1] -$1,$1
    -+[-2,-1] -c[-1] 0,255
  -mv[-1] 0 -done -v +

#@gmic texturize_paper
#@gmic : Add paper texture to selected images.
#@gmic : $ image.jpg --texturize_paper
texturize_paper :
  -e[^-1] "Add paper texture to image$?."
  -v - -repeat @#
    [-1] 30%,30% -noise[-1] 1,2 -r[-1] [-2],[-2],[-2],1,0 -ifft[-1]
    -rm[-1] -shift[-1] 50%,50%,50%,0,2 -sharpen[-1] 1 -n[-1] 1,1.2 -r[-1] [-2]
    -*[-2,-1] -c[-1] [-2],[-2] -rm[-2]
  -mv[-1] 0 -done -v +

#@gmic watermark_visible : _text,0<_opacity<1,_size>0,_angle,_mode={ 0=remove | 1=add },_smoothness>=0
#@gmic : Add or remove a visible watermark on selected images (value range must be [0,255]).
#@gmic : Default values : 'text=(C) G'MIC', 'opacity=0.3', 'size=57', 'angle=25', 'mode=1' and 'smoothness=0'.
#@gmic : $ image.jpg --watermark_visible ,0.7
watermark_visible : -skip "${1=\251\ G'MIC}" -check "${2=0.3}>0 && $2<1 && ${3=57}>0 && ${6=0.5}>=0" -skip ${4=25},${5=1}
  -e[^-1] @{"-if $5 -u Add -else -u Remove -endif"}" visible watermark '$1' on image$?, with opacity $2, size $3, angle $4°."
  -v -
  -repeat @#
    1 -text[-1] "$1",0,0,$3,1,255 -rotate[-1] $4,0,0 -b[-1] $6 -n[-1] 0,255
    -r[-1] [-2],0,2 -+[-1] [-2] -c[-1] 0,255  # Generate opaque watermark image
    -if $5 -*[-1] $2 -*[-2] {1-$2} -+[-2,-1]  # Add watermark
    -else -*[-1] $2 --[-2,-1] -/[-1] {1-$2}   # Remove watermark
    -endif
    -c[-1] 0,255
  -mv[-1] 0 -done
  -v +

#--------------------------------------
#
#@gmic :: Blending and fading
#
#--------------------------------------

#@gmic compose_alpha
#@gmic : Compose selected images two-by-two, using alpha blending.
#@gmic : $ image.jpg --drop_shadow , -resize2dy[-1] 200 -rotate[-1] 20 --compose_alpha
compose_alpha :
  -e[^-1] "Compose image$? two-by-two, using alpha blending."
  -v - -repeat {int(@#/2)}
  -r[-1] [-2],[-2],[-2],100%,0,0,0.5,0.5
    -to_colormode[-2] {a1=!(@{-2,s}%2);a2=!(s%2);max(@{-2,s}-a1,s-a2)+a1}
    -to_colormode[-1] {a=max(@{-2,s},s);a+(a%2)}
    -if {@{-2,s}==2||@{-2,s}==4} # Background has alpha.
      -_compose_alpha[-2] -_compose_alpha[-1]
      -sh[-1] {s-1},{s-1} --*[-3,-1] -rm[-2] -+[-3,-2] --[-2,-1]
      -sh[-1] 0,{s-2} -sh[-2] {@{-2,s}-1},{@{-2,s}-1}
      -max[-1] 1e-10 -/[-2] [-1] -*[-1] 255 -rm[-2,-1]
    -else                        # Background has no alpha.
      -sh[-1] 0,{s-2} -sh[-2] {@{-2,s}-1},{@{-2,s}-1} --[-2] [-4] -*[-2,-1] -/[-1] 255 -rm[-1] -+[-2,-1]
    -endif
  -mv[-1] 0 -done -c 0,255 -v +

_compose_alpha :
  -sh[-1] 0,{s-2} -sh[-2] {@{-2,s}-1},{@{-2,s}-1} -max[-1] 1e-10 -/[-1] 255 -*[-2,-1] -rm[-1]

#@gmic compose_average
#@gmic : Compose selected images two-by-two, using average mode.
#@gmic : $ image.jpg -testimage2d {w},{h} --compose_average
compose_average :
  -e[^-1] "Compose image$? two-by-two, using average mode."
  -v - -repeat {int(@#/2)}
    -to_colormode[-2,-1] 0 -r[-1] [-2],0,0,0.5,0.5 -+[-2,-1] -/[-1] 2
  -mv[-1] 0 -done -v +

#@gmic compose_channels
#@gmic : Compose all channels of each selected image, using specified arithmetic operator (+,-,or,min,...).
#@gmic : Default value : '1=+'.
#@gmic : $ image.jpg --compose_channels and
compose_channels : -skip ${1="+"}
  -e[^-1] "Compose all channels of image$?, with operator '$1'."
  -v - -repeat @#
    -sh[-1] 0,0
    -repeat {@{-2,s}-1} -sh[-2] {$>+1},{$>+1} -$1[-2,-1] -done
    -rm[-1] -r[-1] 100%,100%,100%,1,-1
  -mv[-1] 0 -done -v +

#@gmic compose_colorburn
#@gmic : Compose selected images two-by-two, using color burn mode.
#@gmic : $ image.jpg -testimage2d {w},{h} --compose_colorburn
compose_colorburn :
  -e[^-1] "Compose image$? two-by-two, using colorburn mode."
  -v - -repeat {int(@#/2)}
    -to_colormode[-2,-1] 0 -r[-1] [-2],0,0,0.5,0.5 --[-2] 255 -+[-1] 0.1 -/[-2,-1] -*[-1] 256 -+[-1] 255 -c[-1] 0,255
  -mv[-1] 0 -done -v +

#@gmic compose_darken
#@gmic : Compose selected images two-by-two, using darken mode.
#@gmic : $ image.jpg -testimage2d {w},{h} --compose_darken
compose_darken :
  -e[^-1] "Compose image$? two-by-two, using darken mode."
  -v - -repeat {int(@#/2)}
    -to_colormode[-2,-1] 0 -r[-1] [-2],0,0,0.5,0.5 -min[-2,-1]
  -mv[-1] 0 -done -v +

#@gmic compose_difference
#@gmic : Compose selected images two-by-two, using difference mode.
#@gmic : $ image.jpg -testimage2d {w},{h} --compose_difference
compose_difference :
  -e[^-1] "Compose image$? two-by-two, using difference mode."
  -v - -repeat {int(@#/2)}
    -to_colormode[-2,-1] 0 -r[-1] [-2],0,0,0.5,0.5 --[-2,-1] -abs[-1]
  -mv[-1] 0 -done -v +

#@gmic compose_divide
#@gmic : Compose selected images two-by-two, using divide mode.
#@gmic : $ image.jpg -testimage2d {w},{h} --compose_divide
compose_divide :
  -e[^-1] "Compose image$? two-by-two, using divide mode."
  -v - -repeat {int(@#/2)}
    -to_colormode[-2,-1] 0 -r[-1] [-2],0,0,0.5,0.5 -*[-2] 256 -+[-1] 1 -/[-2,-1] -c[-1] 0,255
  -mv[-1] 0 -done -v +

#@gmic compose_dodge
#@gmic : Compose selected images two-by-two, using dodge mode.
#@gmic : $ image.jpg -testimage2d {w},{h} --compose_dodge
compose_dodge :
  -e[^-1] "Compose image$? two-by-two, using dodge mode."
  -v - -repeat {int(@#/2)}
    -to_colormode[-2,-1] 0 -r[-1] [-2],0,0,0.5,0.5 --[-1] 255.1 -/[-2,-1] -*[-1] -256 -c[-1] 0,255
  -mv[-1] 0 -done -v +

#@gmic compose_edges : smoothness[%]>=0
#@gmic : Compose selected images togethers using edge mode.
#@gmic : $ image.jpg -testimage2d {w},{h} --compose_edges 0.8
compose_edges : -check {$1>=0}
  -e[^-1] "Compose image$? using edge mode, with smoothness $1."
  -if {@#>1} -v - -to_rgb -repeat @#
    --gradient_norm[-1] -+[-1] 1 -b[-1] $1 -n[-1] 1,10 -sqr[-1] -s[-2] c -*[-4--2] [-1] -a[-4--1] c
  -mv[-1] 0 -done -r[1--1] [0],0,0,0.5,0.5 -+ -s[-1] c -/[-4--2] [-1] -rm[-1] -a[-3--1] c -v + -endif

#@gmic compose_exclusion
#@gmic : Compose selected images two-by-two, using exclusion mode.
#@gmic : $ image.jpg -testimage2d {w},{h} --compose_exclusion
compose_exclusion :
  -e[^-1] "Compose image$? two-by-two, using exclusion mode."
  -v - -repeat {int(@#/2)}
    -to_colormode[-2,-1] 0 -r[-1] [-2],0,0,0.5,0.5 --*[-2] [-1] -/[-1] -128 -+[-3--1]
  -mv[-1] 0 -done -v +

#@gmic compose_fade
#@gmic : Compose selected images togethers using a given fading (defined as the latest image).
#@gmic : $ image.jpg -testimage2d {w},{h} 100%,100%,1,1,'cos(y/10)' -normalize[-1] 0,1 --compose_fade
compose_fade :
  -e[^-1] "Compose image$? using fading mode."
  -v - -r[1--1] @{-max_whd},100%,3
  -r[1--2] 100%,100%,100%,@{-max_s} -channels[-1] 0
  -repeat {@#-1}
    ---[-1] $> -abs[-1] --[-1] 1 -*[-1] -1 -max[-1] 0 -*[$>,-1]
  -done
  -rm[-1] -+ -v +

#@gmic compose_freeze
#@gmic : Compose selected images two-by-two, using freeze mode.
#@gmic : $ image.jpg -testimage2d {w},{h} --compose_freeze
compose_freeze :
  -e[^-1] "Compose image$? two-by-two, using freeze mode."
  -v - -repeat {int(@#/2)}
    -to_colormode[-2,-1] 0 -r[-1] [-2],0,0,0.5,0.5 --[-2] 255 -sqr[-2] -+[-1] 0.1 -/[-2,-1] --[-1] 255 -*[-1] -1 -c[-1] 0,255
  -mv[-1] 0 -done -v +

#@gmic compose_grainextract
#@gmic : Compose selected images two-by-two, using grain extract mode.
#@gmic : $ image.jpg -testimage2d {w},{h} --compose_grainextract
compose_grainextract :
  -e[^-1] "Compose image$? two-by-two, using grain extract mode."
  -v - -repeat {int(@#/2)}
    -to_colormode[-2,-1] 0 -r[-1] [-2],0,0,0.5,0.5 --[-2,-1] -+[-1] 128
  -mv[-1] 0 -done -c 0,255 -v +

#@gmic compose_grainmerge
#@gmic : Compose selected images two-by-two, using grain merge mode.
#@gmic : $ image.jpg -testimage2d {w},{h} --compose_grainmerge
compose_grainmerge :
  -e[^-1] "Compose image$? two-by-two, using grain merge mode."
  -v - -repeat {int(@#/2)}
    -to_colormode[-2,-1] 0 -r[-1] [-2],0,0,0.5,0.5 -+[-2,-1] --[-1] 128
  -mv[-1] 0 -done -c 0,255 -v +

#@gmic compose_hardlight
#@gmic : Compose selected images two-by-two, using hard light mode.
#@gmic : $ image.jpg -testimage2d {w},{h} --compose_hardlight
compose_hardlight :
  -e[^-1] "Compose image$? two-by-two, using hard light mode."
  -v - -repeat {int(@#/2)}
    -to_colormode[-2,-1] 0 -r[-1] [-2],0,0,0.5,0.5
    --t[-1] 128
    --*[-3] [-2] -/[-1] 128
    --[-4,-3] 255 -*[-4,-3] -/[-3] 128 --[-3] 255 -*[-3] -1
    -*[-3] [-2] -*[-2] -1 -+[-2] 1 -*[-2,-1]
    -+[-2,-1]
  -mv[-1] 0 -done -v +

#@gmic compose_hue
#@gmic : Compose selected images two-by-two, using hue mode.
#@gmic : $ image.jpg -testimage2d {w},{h} --compose_hue
compose_hue :
  -e[^-1] "Compose image$? two-by-two, using hue mode."
  -v - -repeat {int(@#/2)}
    -to_colormode[-2,-1] 0 -r[-1] [-2],0,0,0.5,0.5 -to_rgba[-2,-1] -sh[-2,-1] 0,2
    -rgb2hsv[-2,-1] -sh[-2] 0,0 -j[-2] [-1] -rm[-5,-3,-1] -hsv2rgb[-1] -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic compose_interpolation
#@gmic : Compose selected images two-by-two, using interpolation mode.
#@gmic : $ image.jpg -testimage2d {w},{h} --compose_interpolation
compose_interpolation :
  -e[^-1] "Compose image$? two-by-two, using interpolation mode."
  -v - -repeat {int(@#/2)}
    -to_colormode[-2,-1] 0 -r[-1] [-2],0,0,0.5,0.5 -*[-2,-1] 0.012271846 -cos[-2,-1] -/[-2,-1] -4 -+[-2,-1] -+[-1] 0.5 -*[-1] 256
  -mv[-1] 0 -done -v +

#@gmic compose_lighten
#@gmic : Compose selected images two-by-two, using lighten mode.
#@gmic : $ image.jpg -testimage2d {w},{h} --compose_lighten
compose_lighten :
  -e[^-1] "Compose image$? two-by-two, using lighten mode."
  -v - -repeat {int(@#/2)}
    -to_colormode[-2,-1] 0 -r[-1] [-2],0,0,0.5,0.5 -max[-2,-1]
  -mv[-1] 0 -done -v +

#@gmic compose_lightness
#@gmic : Compose selected images two-by-two, using lightness mode.
#@gmic : $ image.jpg -testimage2d {w},{h} --compose_lightness
compose_lightness :
  -e[^-1] "Compose image$? two-by-two, using lightness mode."
  -v - -repeat {int(@#/2)}
    -to_colormode[-2,-1] 0 -r[-1] [-2],0,0,0.5,0.5 -to_rgba[-2,-1] -sh[-2,-1] 0,2
    -rgb2lab[-2,-1] -sh[-2] 0,0 -j[-2] [-1],0,0,0,0 -rm[-5,-3,-1] -lab2rgb[-1] -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic compose_luminance
#@gmic : Compose selected images two-by-two, using luminance mode.
#@gmic : $ image.jpg -testimage2d {w},{h} --compose_luminance
compose_luminance :
  -e[^-1] "Compose image$? two-by-two, using luminance mode."
  -v - -repeat {int(@#/2)}
    -to_colormode[-2,-1] 0 -r[-1] [-2],0,0,0.5,0.5 -to_rgba[-2,-1] -sh[-2,-1] 0,2
    -rgb2ycbcr[-2,-1] -sh[-2] 0,0 -j[-2] [-1],0,0,0,0 -rm[-5,-3,-1] -ycbcr2rgb[-1] -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic compose_median
#@gmic : Compose selected images together using median mode.
#@gmic : $ image.jpg -testimage2d {w},{h} --mirror[0] y --compose_median
compose_median :
  -e[^-1] "Compose image$? using median mode."
  -if {@#==1} -return -endif
  -v - -r[1--1] [0],0,0,0.5,0.5 -a z -permute zxyc -s y,-64
  -repeat @# -l[$>]
    -r 100%,{w*100}%
    -s z -median {w} w={w} -columns {int(w/2)} -r 1,{h/$w} -a z
  -endl -done -a y -permute yzxc -v +

#@gmic compose_multiply
#@gmic : Compose selected images two-by-two, using multiply mode.
#@gmic : $ image.jpg -testimage2d {w},{h} --compose_multiply
compose_multiply :
  -e[^-1] "Compose image$? two-by-two, using multiply mode."
  -v - -repeat {int(@#/2)}
    -to_colormode[-2,-1] 0 -r[-1] [-2],0,0,0.5,0.5 -*[-2,-1] -/[-1] 255
  -mv[-1] 0 -done -v +

#@gmic compose_negation
#@gmic : Compose selected images two-by-two, using negation mode.
#@gmic : $ image.jpg -testimage2d {w},{h} --compose_negation
compose_negation :
  -e[^-1] "Compose image$? two-by-two, using negation mode."
  -v - -repeat {int(@#/2)}
    -to_colormode[-2,-1] 0 -r[-1] [-2],0,0,0.5,0.5 -+[-2,-1] --[-1] 255 -abs[-1] --[-1] 255 -*[-1] -1
  -mv[-1] 0 -done -v +

#@gmic compose_overlay
#@gmic : Compose selected images two-by-two, using overlay mode.
#@gmic : $ image.jpg -testimage2d {w},{h} --compose_overlay
compose_overlay :
  -e[^-1] "Compose image$? two-by-two, using overlay mode."
  -v - -repeat {int(@#/2)}
    -to_colormode[-2,-1] 0 -r[-1] [-2],0,0,0.5,0.5
    --t[-2] 128
    --*[-3] [-2] -/[-1] 128
    --[-4,-3] 255 -*[-4,-3] -/[-3] 128 --[-3] 255 -*[-3] -1
    -*[-3] [-2] -*[-2] -1 -+[-2] 1 -*[-2,-1]
    -+[-2,-1]
  -mv[-1] 0 -done -v +

#@gmic compose_reflect
#@gmic : Compose selected images two-by-two, using reflect mode.
#@gmic : $ image.jpg -testimage2d {w},{h} --compose_reflect
compose_reflect :
  -e[^-1] "Compose image$? two-by-two, using reflect mode."
  -v - -repeat {int(@#/2)}
    -to_colormode[-2,-1] 0 -r[-1] [-2],0,0,0.5,0.5 -sqr[-2] --[-1] 255.1 -/[-2,-1] -*[-1] -1 -c[-1] 0,255
  -mv[-1] 0 -done -v +

#@gmic compose_rgba
#@gmic : Compose selected images two-by-two, as RGBA images over RGB backgrounds.
compose_rgba :
  -e[^-1] "Compose image$? two-by-two, using alpha blending."
  -v - -to_rgb[0--1:2] -compose_alpha -v +

#@gmic compose_saturation
#@gmic : Compose selected images two-by-two, using saturation mode.
#@gmic : $ image.jpg -testimage2d {w},{h} --compose_saturation
compose_saturation :
  -e[^-1] "Compose image$? two-by-two, using saturation mode."
  -v - -repeat {int(@#/2)}
    -to_colormode[-2,-1] 0 -r[-1] [-2],0,0,0.5,0.5 -to_rgba[-2,-1] -sh[-2,-1] 0,2
    -rgb2hsv[-2,-1] -sh[-2] 1,1 -j[-2] [-1],0,0,0,1 -rm[-5,-3,-1] -hsv2rgb[-1] -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic compose_screen
#@gmic : Compose selected images two-by-two, using screen mode.
#@gmic : $ image.jpg -testimage2d {w},{h} --compose_screen
compose_screen :
  -e[^-1] "Compose image$? two-by-two, using screen mode."
  -v - -repeat {int(@#/2)}
    -to_colormode[-2,-1] 0 -r[-1] [-2],0,0,0.5,0.5 --[-2,-1] 255 -*[-2,-1] -/[-1] 256 --[-1] 255 -*[-1] -1
  -mv[-1] 0 -done -v +

#@gmic compose_shapeaverage
#@gmic : Compose selected images two-by-two, using shape average mode.
#@gmic : $ image.jpg --luminance -stencil[-1] 1 --compose_shapeaverage
compose_shapeaverage :
  -e[^-1] "Compose image$? two-by-two, using shape average mode."
  -v - -repeat {int(@#/2)} -l[-2,-1]
    -channels[-1] 0 -t[-1] 50% -label_fg[-1] 0 nb={iM+1} -*[-1] 256
    -rv[-2,-1] m={im} M={iM} -n[-1] 0,255 -s[-1] c -+[1--1] [0]
    -repeat {@#-1}
      -histogram[-1] {$nb*256},0,{$nb*256-1}
      -i[-2] 256,1,1,1,'x' -r[-2] {w},1,1,1,0,2 -*[-2] [-1] -r[-2,-1] $nb,1,1,1,2 -/[-2,-1]
    -mv[-1] 1 -done
    -/[0] 256 -a[1--1] c -*[-1] {($M-$m)/256} -+[-1] $m -point[-1] 0,0,0,1,0 -map[0] [-1] -rm[-1]
  -endl -mv[-1] 0 -done -v +

#@gmic compose_softlight
#@gmic : Compose selected images two-by-two, using soft light mode.
#@gmic : $ image.jpg -testimage2d {w},{h} --compose_softlight
compose_softlight :
  -e[^-1] "Compose image$? two-by-two, using soft light mode."
  -v - -repeat {int(@#/2)}
    -to_colormode[-2,-1] 0 -r[-1] [-2],0,0,0.5,0.5 -/[-2,-1] 256 --*[-2] [-1] -*[-1] 2 -sqr[-3] -*[-2] [-3] -*[-2] -2 -+[-3--1] -*[-1] 256
  -mv[-1] 0 -done -v +

#@gmic compose_stamp
#@gmic : Compose selected images two-by-two, using stamp mode.
#@gmic : $ image.jpg -testimage2d {w},{h} --compose_stamp
compose_stamp :
  -e[^-1] "Compose image$? two-by-two, using stamp mode."
  -v - -repeat {int(@#/2)}
    -to_colormode[-2,-1] 0 -r[-1] [-2],0,0,0.5,0.5 -*[-1] 2 -+[-2,-1] --[-1] 255 -c[-1] 0,255
  -mv[-1] 0 -done -v +

#@gmic compose_value
#@gmic : Compose selected images two-by-two, using value mode.
#@gmic : $ image.jpg -testimage2d {w},{h} --compose_value
compose_value :
  -e[^-1] "Compose image$? two-by-two, using value mode."
  -v - -repeat {int(@#/2)}
    -to_colormode[-2,-1] 0 -r[-1] [-2],0,0,0.5,0.5 -to_rgba[-2,-1] -sh[-2,-1] 0,2
    -rgb2hsv[-2,-1] -sh[-2] 2,2 -j[-2] [-1],0,0,0,2 -rm[-5,-3,-1] -hsv2rgb[-1] -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic compose_xor
#@gmic : Compose selected images two-by-two, using xor mode.
#@gmic : $ image.jpg -testimage2d {w},{h} --compose_xor
compose_xor :
  -e[^-1] "Compose image$? two-by-two, using xor mode."
  -v - -repeat {int(@#/2)}
    -to_colormode[-2,-1] 0 -r[-1] [-2],0,0,0.5,0.5 -xor[-2,-1]
  -mv[-1] 0 -done -v +

#@gmic fade_diamond : 0<=_start<=100,0<=_end<=100
#@gmic : Create diamond fading from selected images.
#@gmic : Default values : 'start=80' and 'end=90'.
#@gmic : $ image.jpg -testimage2d {w},{h} --fade_diamond 80,85
fade_diamond : -skip ${1=70},${2=90}
  -e[^-1] "Create ($1%,$2%) diamond-shaped fading from image$?."
  -v - -repeat {int(@#/2)}
    (0,1,0;1,1,1;0,1,0) -_fade $1,$2
  -mv[-1] 0 -done -v +

#@gmic fade_linear : _angle,0<=_start<=100,0<=_end<=100
#@gmic : Create linear fading from selected images.
#@gmic : Default values : 'angle=45', 'start=30' and 'end=70'.
#@gmic : $ image.jpg -testimage2d {w},{h} --fade_linear 45,48,52
fade_linear : -skip ${1=45},${2=30},${3=70}
  -e[^-1] "Create ($2%,$3%) linear fading from image$?, with angle $1°."
  -v - -repeat {int(@#/2)}
     64,64,1,1,"x*cos($1*pi/180) + y*sin($1*pi/180)" -_fade $2,$3
  -mv[-1] 0 -done -v +

_fade :
  -r[-2] [-3],5 -r[-1] [-2],3 -c[-1] $1%,$2% -n[-1] 0,1
  -*[-2] [-1] --[-1] 1 -*[-3,-1] -rv[-2,-1] --[-2,-1]

#@gmic fade_radial : 0<=_start<=100,0<=_end<=100
#@gmic : Create radial fading from selected images.
#@gmic : Default values : 'start=30' and 'end=70'.
#@gmic : $ image.jpg -testimage2d {w},{h} --fade_radial 30,70
fade_radial : -skip ${1=30},${2=70}
  -e[^-1] "Create ($1%,$2%) radial fading from image$?."
  -v - -repeat {int(@#/2)}
    100%,100% -point[-1] 50%,50%,0,1,1 -distance[-1] 1 -_fade $1,$2
  -mv[-1] 0 -done -v +

#@gmic fade_x : 0<=_start<=100,0<=_end<=100
#@gmic : Create horizontal fading from selected images.
#@gmic : Default values : 'start=30' and 'end=70'.
#@gmic : $ image.jpg -testimage2d {w},{h} --fade_x 30,70
fade_x : -skip ${1=30},${2=70}
  -e[^-1] "Create ($1%,$2%) horizontal fading from image$?."
  -v - -repeat {int(@#/2)}
    (0,1) -_fade $1,$2
  -mv[-1] 0 -done -v +

#@gmic fade_y : 0<=_start<=100,0<=_end<=100
#@gmic : Create vertical fading from selected images.
#@gmic : Default values : 'start=30' and 'end=70'.
#@gmic : $ image.jpg -testimage2d {w},{h} --fade_y 30,70
fade_y : -skip ${1=30},${2=70}
  -e[^-1] "Create ($1%,$2%) vertical fading from image$?."
  -v - -repeat {int(@#/2)}
    (0;1) -_fade $1,$2
  -mv[-1] 0 -done -v +

#@gmic fade_z : 0<=_start<=100,0<=_end<=100
#@gmic : Create transversal fading from selected images.
#@gmic : Default values : 'start=30' and 'end=70'.
fade_z : -skip ${1=30},${2=70}
  -e[^-1] "Create ($1%,$2%) transversal fading from image$?."
  -v - -repeat {int(@#/2)}
    (0/1) -_fade $1,$2
  -mv[-1] 0 -done -v +

#---------------------------------------------
#
#@gmic :: Image sequences
#
#---------------------------------------------

#@gmic animate
#@gmic : filter_name,"param1_start,..,paramN_start","param1_end,..,paramN_end",nb_frames>=0,_output_frames={ 0 | 1 },_output_filename |
#@gmic : delay>0\n
#@gmic : Animate filter from starting parameters to ending parameters.
#@gmic : Default value : 'delay=30'.
#@gmic : $ image.jpg -animate flower,"0,3","20,8",9 -append_tiles 3,3
animate : -skip ${1=30},${2=0},${3=""},${4=0},${5=1},"${6=}"
  -if {isval($1)}
    -if $2 -e[0--4] "Animate image$?, with a delay of $1 ms, and ping-pong mode."
    -else -e[0--4] "Animate image$?, with a delay of $1 ms."
    -endif
    -if {!@#} -return -endif
    -v -
    speed=$1    # Animation speed
    pause=-1    # Pause mode.
    direction=1 # Animation direction.
    frame=0     # Current frame.
    -do
      -w[$frame] -1,-1,1,0,@{$frame,b}.@{$frame,x}
      frame={$frame+$direction}
      -if $2
        -if {$frame==-1} frame=0 direction=1
        -elif {$frame==@#} frame={@#-1} direction=-1
        -endif
      -else frame={$frame%@#}
      -endif
      -wait $speed
      -if {(@{!,CTRLLEFT}" || "@{!,CTRLRIGHT})" && "@{!,D}} -w[] {@{!,w}*1.5},{@{!,h}*1.5} -wait -1 -endif # Increase window size.
      -if {(@{!,CTRLLEFT}" || "@{!,CTRLRIGHT})" && "@{!,C}} -w[] {@{!,w}/1.5},{@{!,h}/1.5} -wait -1 -endif # Decrease window size.
      -if {(@{!,CTRLLEFT}" || "@{!,CTRLRIGHT})" && "@{!,R}} -w[] @{0,w},@{0,h} -wait -1 -endif             # Reset window size.
      -if @{!,o} speed={min(500,max(10,$speed-10*@{!,o}))} -wait -1 -endif
      -if @{!,SPACE}
        -if {$pause>=0} direction=$pause pause=-1
        -else pause=$direction direction=0 -endif
        -wait -1
      -endif

    -while {@!" && "!@{!,Q}" && "!@{!,ESC}} -v +
  -else
    -e[0--3] "Compute animated version of filter '$1', from parameters $2 to $3 with $4 frames."
    -if {!($5||narg("$6"))} -return -endif
    -v - ($2) ($3) -y[-2,-1] x -a[-2,-1] y -r[-1] 100%,$4,1,1,3 -mv[-1] 0 -progress 0
    -repeat {@#-1}
      -v + -e[] " > Animate image ["$>"]" -v -
      -repeat $4 --l[0,1]
        -$1[-1] @{0,{$>*@{0,w}}-{($>+1)*@{0,w}-1}} -rm[0]
        -if {narg("$6")} -o @{"-filename \"$6\","@{>,-2},$>} -endif
        -if {!$5} -rm -endif
        -progress {100*($>+1)/$4}
        -v + -e[] "\r > Animate image ["@{>,-2}"] : Frame "{$>+1}"/$4    " -v -
      -endl -done
    -rm[1] -done -rm[0] -v +
  -endif

#@gmic morph : nb_frames>0,_smoothness>=0,_precision>0
#@gmic : Create morphing sequence between selected images.
#@gmic : Default values : 'smoothness=0.1' and 'precision=5'.
#@gmic : $ image.jpg --rotate 20,1,1,50%,50% -morph 9 -append_tiles 3,3
morph : -skip ${2=0.1},${3=5}
  -e[^-1] "Create morphing sequence between image$?, with $1 intra-frames, smoothness $2 and precision $3.\n"
  -v - -r[1--1] [0],3 -i[0] (@#) --[0] 1 -repeat @0
   -v + -e[] "\r > Morph image "$>" to image "{$>+1}".    " -v -
    --equalize[-2,-1] 256 -n[-2,-1] 0,255
    --displacement[-1] [-2],$2,$3 --warp[-5] [-1],1,1,1,$1 -a[-$1--1] z -rm[-2]
    --displacement[-3] [-2],$2,$3 --warp[-5] [-1],1,1,1,$1 -a[-$1--1] z -rm[-7--4,-2]
    (1/0) -r[-1] [-2],3 -*[-3] [-1] -*[-2,-1] -mirror[-1] z -+[-2,-1] -s[-1] z
    -mv[-$1--1] 1 -mv[1] @#
  -done -mv[-1] 1 -rm[0] -v +

#@gmic register_nonrigid : _smoothness>=0,_precision>0,_nb_scale>=0
#@gmic : Register selected images with non-rigid warp.
#@gmic : Default values : 'smoothness=0.2', 'precision=6' and 'nb_scale=0(auto)'.
#@gmic : $ image.jpg --rotate 20,1,1,50%,50% --register_nonrigid , -remove[-2]
register_nonrigid : -skip ${1=0.2},${2=5},${3=0}
  -e[^-1] "Register image$? with non-rigid warp, smoothness $1, precision $2 and $3 scale(s)."
  -v - --equalize[0] 256 -n[-1] 0,255 -mv[-1] 1
  -repeat @# -if {$>>1}
    --equalize[-1] 256 -n[-1] 0,255 --displacement[1] [-1],$1,$2,$3 -rm[-2]
    -warp[-2] [-1],1,1,1 -rm[-1]
  -mv[-1] 2 -endif -done -rm[1] -v +

#@gmic register_rigid : _smoothness>=0
#@gmic : Register selected images with rigid warp.
#@gmic : Default value : 'smoothness=1'.
#@gmic : $ image.jpg --shift 30,20 --register_rigid , -remove[-2]
register_rigid : -skip ${1=1}
  -e[^-1] "Register image$? with rigid warp and smoothness $1."
  -v - --equalize[0] 256 -b[-1] $1 -n[-1] 0,255 -mv[-1] 1
  -repeat @# -if {$>>1}
    --equalize[-1] 256 -b[-1] $1 -n[-1] 0,255 --phase_correlation[1,-1] -rm[-2] -*[-1] -1 -round[-1] 1
    -shift[-2] @-1,0,1 -rm[-1]
  -mv[-1] 2 -endif -done -rm[1] -v +

#-----------------------------
#
#@gmic :: Interactive demos
#
#-----------------------------

#@gmic x_blobs
#@gmic : Launch the blobs editor.
x_blobs :
  -e[] "\n
------ Blobs editor --------------------------\n
----\n
---- Mouse to insert/move/delete blobs.\n
---- Keys 'ESC' or 'Q' to exit.\n
----\n
-----------------------------------------------------"
  -v -

  # Create background image [0].
  -rm (0;0^0;128^0;255) -r[-1] 350,350,1,3,3 -flower[-1] 30,8,0,0,0.5,0.5,1 -water[-1] 20
  -w {w},{h},0,0,"[G'MIC] Blobs editor"

  # Start event loop.
  moving=-1
  -do
    x=@{!,x} y=@{!,y} b=@{!,b} nearest=-1

    # Render image of blobs and find nearest blob to mouse pointer.
    -if {@#>1}
      @{!,w},@{!,h},1,2
      -repeat @{1,h}
        r={@{1,2}*(1+@{1,3}*cos(@{1,4}+@{1,5}*@|*1000))}
        -ellipse[-1] @{1,0,1},$r,$r,0,1,@{1,6-7}
        d={sqrt(($x-@{1,0})^2+($y-@{1,1})^2)}
        -if {$d<$r} nearest=$> -endif
      -shift[1] 0,-1,0,0,2 -done
      -b[-1] 15
      --norm[-1] --ge[-1] 50 -le[-2] 40 -*[-3,-1]
      --*[0,-1] -rm[-2] -rv[-2,-1] -*[-1] 1.6 -c[-1] 0,255 -+[-2,-1]
      -w[-1] {w},{h} -rm[-1]
    -else
      --text_outline[0] "G'MIC Blobs Editor",65,40,24,3,1,200,128,255
      -text[-1] "* Left mouse button : Create and move blobs.\n\n\
                 * Right mouse button : Remove blob.\n\n\
                 * Middle mouse button : Remove all blobs.\n\n\
                 * Key 'ESC' or 'Q' : Quit.\n\n\
                 * Colors and sizes of appearing blobs are\n   chosen randomly",\
                60,120,13,1,255
      -w[-1] {w},{h} -rm[-1]
    -endif
    -wait 20

    # Manage blob insertion, removal or move.
    -if {$x<0||$y<0} -continue -endif
    -if {$b&1}
      -if {$nearest>=0" || "$moving>=0} # Move existing blob.
        -if {$moving<0} moving=$nearest -endif
        -=[1] $x,0,$moving -=[1] $y,1,$moving
        -else # Insert new blob.
          (@{!,x},@{!,y},{?(20,50)},{?(-0.3,0.3)},{?(0,pi/2)},{?(0,0.009)},{?(64,255)},{?(64,255)}) -a[^0] y
          moving={h-1}
        -endif
    -elif {$b&2} # Remove existing blob.
      -if {$nearest>=0} -l[1] -s y -rm[$nearest] -a y -endl nearest=-1 -endif
    -elif {$b&4} # Remove all blobs.
      -rm[^0]
    -else
      moving=-1
    -endif

  -while {@!" && "!@{!,ESC}" && "!@{!,Q}}
  -rm -w 0 -v +

#@gmic x_fire
#@gmic : Launch the fire demo.
x_fire : -skip "${1=G'MIC}"
  -e[] "\n
------ Fire demo ------------------------\n
----\n
---- Keys 'ESC' or 'Q' to exit.\n
----\n
-----------------------------------------"
  -v -

  # Init image data.
  -i[0] 100,32 -w[0] 600,300,0,0,"[G'MIC] Fire demo"
  -i[1] (0,255,255,255,255^0,0,255,255,255^0,0,0,128,255) -r[1] 256,1,1,3,3
  -i[2] (0,0,0;0,0,0;1,1,1;0,1,0) -*[2] 0.21
  -text3d "$1",34,3,1 -mv[-1] 3 -c3d[3] -n3d[3] -*3d[3] 320 -col3d[3] 255,205,130 -db3d 0 -f3d 300
  100,100 -rand[-1] 0,255 -ellipse[-1] 50%,50%,5,5,0,1,300 -b[-1] 10
  -sharpen[-1] 1000 -shrink_xy[-1] 1 -n[-1] 0,255 -to_rgb[-1] -light3d [-1] -rm[-1]

  # Start animation loop.
  mode=@* angle=0
  -do
    -correlate[0] [2]                                                # Apply fire effect.
    @{0,w},1 -rand[-1] 128,256 -j[0] [-1],0,{@{0,h}-1} -rm[-1]   # Add new random values at the bottom line.
    --r[0] 400,200,1,1,3 -map[-1] [1]                                # Map fire palette
    --r3d[3] 0,1,0,$angle -m3d 5 -object3d[-2] [-1],50%,50%          # Draw 3d object.
    -*3d[-1] 0.25,0.16,1 -m3d 3 -object3d[0] [-1],50%,50%
    -rm[-1]
    angle={$angle+3}                                                 # Update 3d angle.
    -w[-1] -rm[-1] -wait 40                                          # Display 3d object.
  -while {@!" && "!@{!,ESC}" && "!@{!,Q}}

  # Exit properly.
  -m3d $mode -rm[0-3] -w 0
  -v +

#@gmic x_fireworks
#@gmic : Launch the fireworks demo.
x_fireworks :
  -e[] "\n
------ Fireworks demo -------------------\n
----\n
---- Keys 'ESC' or 'Q' to exit.\n
----\n
-----------------------------------------"
  -v - -l[]
  time=0
  (0;64^0;32^128;0) -r 256,128,1,3,3          # [-2] = Background (color gradient).
  [-1]                                        # [-1] = Rendered image.
  -w[-1] 512,256,0,0,"[G'MIC] Fireworks demo" # Display window.
  -do                                         # Start animation loop.
    time={$time-1}
    -if {@#==2\ ||\ $time<0} # Insert new rocket.
      -i[0] ({?(w)},\        # X-position
             {h},\           # Y-position
             {?(-3,3)},\     # X-velocity
             {?(2)-5},\      # Y-velocity
             {30+?(20)},\    # Time of explosion
             1.5,\           # Radius
             255,255,255)    # Color
      time={?(80)}           # Elapsed time until next rocket.
    -endif
    -*[-1] 0.99                   # Create fading effect with previous frames.
    -j[-1] [-2],0,0,0,0,0.2   # Add background.
    i=0
    -repeat {@#-2}
      to_be_removed=0
      radius={if(@{$i,4}>0,@{$i,5}/3,@{$i,5}*(1+2*(@{$i,4}+2)/120))}
      -ellipse[-1] @{$i,0},@{$i,1},@{$i,5},{max(0.5,$radius)},{atan2(@{$i,3},@{$i,2})*180/pi},0.6,@{$i,6-8}  # Draw rocket.
      (@{$i,2},@{$i,3},0,0.09,-1,0,0,0,0) -+[$i,-1] # Compute new position of the rocket.
      -if {@{$i,0}<0\ ||\ @{$i,0}>=w\ ||\ @{$i,1}>=h\ ||\ $radius<0} to_be_removed=1 -endif # Discard if rocket disappear.
      -if {@{$i,4}<0\ &&\ @{$i,4}>=-1} # In case of explosion -> Split current rocket into several colorful rockets.
        color={min(255,80+?(200))},{min(255,80+?(200))},{min(255,80+?(200))}
        radius={?(10)}
        N={5+?(10)}
        -repeat $N
          angle={$>*2*pi/$N}
          -i[-3] (@{$i,0,1},{2*cos($angle)+@{$i,2}/1.5},{2*sin($angle)+@{$i,3}/1.5},-2,$radius,$color)
        -done
        to_be_removed=1
      -endif
      -if $to_be_removed -rm[$i] -else i={$i+1} -endif  # If processed rocket has to be removed.
    -done
    -w[-1] -wait 20  # Display rendered frame.
  -while {@!" && "!@{!,ESC}" && "!@{!,Q}}
  -endl -rm[0--2] -w[] 0 -v +

#@gmic x_fisheye
#@gmic : Launch fish-eye demo.
x_fisheye :
  -e[] "\n
------ Fish-eye demo --------------------\n
----\n
---- Mouse pointer moves fish-eye center.\n
---- Mouse buttons set fish-eye size.\n
---- Keys 'ESC' or 'Q' to exit.\n
----\n
-----------------------------------------"

  -v -
  -if {@#>0} -a x -n 0,255 -r2dy 220 -else
  120,90,1,3 -rand[-1] 0,255 -plasma[-1] 0.3,3 -n 0,255
  -text "  G'MIC\nFISH-EYE\n  DEMO",15,13,24,1,255 -resize2x -b 5 -sharpen 1000
  -f i+150-4*abs(y-h/2) -c[-1] 0,255 -frame_fuzzy[-1] 15,10,15,1.5,0 -to_rgb[-1]
  -endif
  mode=@* -m3d 3 -torus3d 20,6 -col3d[-1] {?(30,255)},{?(30,255)},{?(30,255)} --r3d[-1] 1,0,0,90
  -col3d[-1] {?(30,255)},{?(30,255)},{?(30,255)} -+3d[-1] 15 -+3d[-2,-1] -db3d 0 -c3d[-1]
  R=30
  -w[-2] {2*@{-2,w}},{2*@{-2,h}},0,0,"[G'MIC] Fish-Eye Demo"
  -do
    -wait 40
    -if {@{!,b}==1} R={min(80,$R+8)} -endif
    -if {@{!,b}==2} R={max(3,$R-8)} -endif
    --object3d[-2] [-1],{50+30*cos(@|*2.5)}%,{50+30*sin(@|*1.6)}%,{50+330*sin(@|*2.6)},0.7,0 -r3d[-2] 1,0.2,0.6,3
    -if {@{!,x}>=0}
    -fisheye[-1] {@{!,x}*100/@{!,w}},{@{!,y}*100/@{!,h}},$R
    -endif
    -w[-1] -rm[-1]
    -if {@!==0" || "@{!,ESC}" || "@{!,Q}} -rm[-2,-1] -m3d $mode -w 0 -v + -return -endif
    -if {(@{!,CTRLLEFT}" || "@{!,CTRLRIGHT})" && "@{!,D}} -w[] {@{!,w}*1.5},{@{!,h}*1.5} -wait -1 -endif
    -if {(@{!,CTRLLEFT}" || "@{!,CTRLRIGHT})" && "@{!,C}} -w[] {@{!,w}/1.5},{@{!,h}/1.5} -wait -1 -endif
    -if {(@{!,CTRLLEFT}" || "@{!,CTRLRIGHT})" && "@{!,R}} -w[] @{0,w},@{0,h} -wait -1 -endif
  -while 1

#@gmic x_fourier
#@gmic : Launch fourier filtering demo.
x_fourier :
  -e[] "\n
------ Fourier-filtering demo -----------------------------------\n
----\n
---- Mouse buttons on the right image to set min/max frequencies.\n
---- Keys 'ESC' or 'Q' to exit.\n
----\n
-----------------------------------------------------------------"
  -v -
  -if {!@#} -testimage2d 400 -endif
  -repeat @# -l[$>]

    # Init variables.
    need_update=1  # need_update (boolean)
    freqmin=0      # min freq. (in %)
    freqmax=100    # max freq. (in %)

    -if {w>3*@{!,u}/5} -r2dx[-1] {3*@{!,u}/10} -endif  # Reduce image size if necessary.
    -if {h>3*@{!,v}/5} -r2dy[-1] {3*@{!,v}/5} -endif

    # Compute fourier transform.
    --fft[-1] -nm[-2] real -nm[-1] imag

    # Generate log-magnitude image.
    --sqr[real,imag] -+[-2,-1] -sqrt[-1] -+[-1] 1 -log[-1]
    -n[-1] 0,255 -shift[-1] 50%,50%,0,0,2 -to_colormode[-1] @{-2,s}
    -nm[-1] logmag

    # Enter user event-loop.
    -do

      -if $need_update # If image must be updated.

        # Generated filtering mask.
        -i[mask] 100%,100%
        r={sqrt(w^2+h^2)*$freqmax/200} -ellipse[mask] 50%,50%,$r,$r,0,1,1
        r={max(0,sqrt(w^2+h^2)*$freqmin/200-1)} -if $r -ellipse[mask] 50%,50%,$r,$r,0,1,0 -endif

        # Compute filtered log-magnitude.
        --*[logmag] [mask] -+[-1] [mask] -/[-1] 2 -n[-1] 0,255

        # Compute filtered fourier representation.
        -shift[mask] -50%,-50%,0,0,2
        --*[real,imag] [mask]
        -rm[-4]

        # Compute filtered image by inverse fourier.
        -ifft[-2,-1] -rm[-1] -n[-1] 0,255

        # Display filtered image.
        -rv[-2,-1]
        -if @! -r[-2,-1] {@{!,w}/2},@{!,h} -endif
        -text[-1] "Freq. Min/Max = "{int($freqmin)}"% / "{int($freqmax)}"%",5,5,13,1,255
        -w[-2,-1] -1,-1,0,0,"[G'MIC] Fourier Filtering Demo"
        -rm[-2,-1]
        need_update=0

      -endif

      -wait

      -if {@{!,b}" && "@{!,x}>=@{!,w}/2}  # If mouse button pressed on the right pane.
        r={200*sqrt((@{!,x}-3*@{!,w}/4)^2+(@{!,y}-@{!,h}/2)^2)/\ # Compute selected radius (in %).
           sqrt((@{!,w}/2)^2+@{!,h}^2)}
        -if {@{!,b}&1} freqmax=$r        # Update max freq. if left button.
        -else freqmin={max(0,$r-3)}      # Update min freq. if other button.
        -endif
        -if {$freqmin>=$freqmax} freqmin=$freqmax -endif   # Check that the min/max freq. are ordered.
        need_update=1                                      # Tell that the image must be updated.
      -endif

      -if @{!,r} need_update=1 -endif
      -if {(@{!,CTRLLEFT}" || "@{!,CTRLRIGHT})" && "@{!,D}} -w[] {@{!,w}*1.5},{@{!,h}*1.5} need_update=1 -endif # Increase window size.
      -if {(@{!,CTRLLEFT}" || "@{!,CTRLRIGHT})" && "@{!,C}} -w[] {@{!,w}/1.5},{@{!,h}/1.5} need_update=1 -endif # Decrease window size.
      -if {(@{!,CTRLLEFT}" || "@{!,CTRLRIGHT})" && "@{!,R}} -w[] {2*@{0,w}},@{0,h} need_update=1 -endif         # Reset window size.

    -while {@!" && "!@{!,ESC}" && "!@{!,Q}}
    -rm[-3--1]  # Clean images.
  -endl -done -w 0 -rm -v +

#@gmic x_histogram
#@gmic : Launch histogram demo.
x_histogram :
  -e[] "\n
------ Histogram demo -------------------------------\n
----\n
---- Mouse to set parameters.\n
---- Right button or key 'SPACE' to reset.\n
---- Keys 'ESC' or 'Q' to exit.\n
----\n
-----------------------------------------------------"
  -v -
  -if {!@#} -testimage2d 300,300 -else -k[0] -to_rgb -r2dy 300 -if {w>800} -r 800,100%,1,3,2 -endif -n 0,255 -endif

  # Prepare image layout.
  --frame[-1] 1,1,0
  300,{h},1,3,220
  -text[-1] "Gamma :",5,0,16,1,0
  -text[-1] "Contrast :",5,50,16,1,0
  -text[-1] "Brightness :",5,100,16,1,0
  -text[-1] "Smoothness :",5,150,16,1,0
  -text[-1] "Sharpness :",5,200,16,1,0
  -text[-1] "Clusters :",5,250,16,1,0
  -a[-2,-1] x
  {w},200,1,3,255
  -grid[-1] 10%,10%,0,0,0.3,0xCCCCCCCC,0
  -polygon[-1] 4,0,0,100%,0,100%,100%,0,100%,1,0xFFFFFFFF,0
  -axes[-1] 0,255,1,0,13,1,0
  -frame[-2,-1] 5,5,220
  -a[-2,-1] y

  # Initialize variables.
  clusters=64 sharpness=0 smoothness=0 contrast=1 brightness=0 gamma=1

  # Start event loop.
  -do

    # Render corrected image and insert it in canvas.
    [0]
    ia={ia}
    -if $gamma -/[-1] 255 -^[-1] {1/$gamma} -*[-1] 255 -endif
    --[-1] $ia -*[-1] $contrast -+[-1] $brightness -+[-1] $ia
    -b[-1] $smoothness
    -sharpen[-1] $sharpness
    -c[-1] 0,255
    --j[-2] [-1],6,6

    # Render parameter sliders.
    sx={@{0,w}+12}
    -_x_histogram[-1] {$gamma*100/4} -j[-2] [-1],$sx,25 -rm[-1]
    -_x_histogram[-1] {$contrast*100/4} -j[-2] [-1],$sx,75 -rm[-1]
    -_x_histogram[-1] {($brightness+128)*100/256} -j[-2] [-1],$sx,125 -rm[-1]
    -_x_histogram[-1] {$smoothness*100/10} -j[-2] [-1],$sx,175 -rm[-1]
    -_x_histogram[-1] {$sharpness*100/2000} -j[-2] [-1],$sx,225 -rm[-1]
    -_x_histogram[-1] {$clusters*100/256} -j[-2] [-1],$sx,275 -rm[-1]

    # Render corresponding histogram.
    --s[-2] c -histogram[-3--1] $clusters,0,255 -/[-3--1] {3*@{0,wh}/$clusters} -rm[-5]
    --z[-4] 5,317,{@{-4,w}-5},{@{-4,h}-6}
    -graph[-1] [-4],3,0,1,0,0.2,255,0,0
    -graph[-1] [-3],3,0,1,0,0.2,0,255,0
    -graph[-1] [-2],3,0,1,0,0.2,0,0,255
    -rm[-4--2]
    -j[-2] [-1],5,317 -rm[-1]

    # Display rendering.
    -w[-1] {w},{h},0,0,"[G'MIC] Histogram demo" -rm[-1]
    -wait

    # Manage user interactions.
    -if {@{!,b}&1\ &&\ @{!,x}>=@{0,w}-10}
      -if {@{!,y}>=25\ &&\ @{!,y}<=42}
        gamma={max(0,min(4,(@{!,x}-$sx)*4/280))}
      -elif {@{!,y}>=75\ &&\ @{!,y}<=92}
        contrast={max(0,min(4,(@{!,x}-$sx)*4/280))}
      -elif {@{!,y}>=125\ &&\ @{!,y}<=142}
        brightness={max(-128,min(128,(@{!,x}-$sx)*256/280-128))}
      -elif {@{!,y}>=175\ &&\ @{!,y}<=192}
        smoothness={max(0,min(10,(@{!,x}-$sx)*10/280))}
      -elif {@{!,y}>=225\ &&\ @{!,y}<=242}
        sharpness={max(0,min(2000,(@{!,x}-$sx)*2000/280))}
      -elif {@{!,y}>=275\ &&\ @{!,y}<=292}
        clusters={max(2,min(256,(@{!,x}-$sx)*256/280))}
      -endif
    -endif
    -if {@{!,b}&2\ ||\ @{!,SPACE}} clusters=64 sharpness=0 smoothness=0 contrast=1 brightness=0 gamma=1 -endif
  -while {@!" && "!@{!,ESC}" && "!@{!,Q}}
  -w 0 -rm -v +

_x_histogram :
  val={max(0,min(100,$1))}
  280,2,1,3,255 -line[-1] 0,0,$val%,0,1,0,255,0 -line[-1] 0,1,$val%,1,1,240,255,62 -r[-1] 100%,16,1,3,3
  1 -text[-1] {round($val)}%,0,0,20,1,1 --*[-1] -255 -+[-1] 255 -r[-1] 100%,100%,1,3
  -j[-3] [-1],{(280-w)/2},{(16-h)/2},0,0,1,[-2] -rm[-2,-1]
  -r[-1] {w+2},{h+2},1,3,0,0,0.5,0.5

#@gmic x_hough
#@gmic : Launch hough transform demo.
x_hough :
  -e[] "\n
------ Hough-transform demo -----------------------------------\n
----\n
---- Mouse buttons on the vote image to draw corresponding line.\n
---- Mouse buttons on the image to vote for all lines crossing.\n
---- the clicked point.\n
---- Key 'SPACE' to reset the hough window.\n
---- Keys 'ESC' or 'Q' to exit.\n
----\n
-----------------------------------------------------------------"
  -v -
  -if {!@#} -testimage2d 400 -endif
  -n 0,255 -repeat @# -l[$>]
    -r[-1] @{-fitscreen\ {w},{h}},1,100%,3  # Resize to fit screen if necessary.

    rhomax={sqrt(w^2+h^2)/2}
    --b[-1] 1.5 -hough[-1] 512,400 -b[-1] 0.5 -+[-1] 1 -log[-1] -n[-1] 0,255
    -w[-2] -1,-1,0,0,"[G'MIC] Image" -w1[-1] -1,-1,0,0,"[G'MIC] Hough Transform"

    -do
      -wait

      -if @{!,b} # When clicking on the image.
        x0={@{!,x}-@{!,w}/2}
        y0={@{!,y}-@{!,h}/2}
        rho0={sqrt(($x0)^2+($y0)^2)}
        theta0={atan2($y0,$x0)}
        (0,{2*pi}) ($theta0,{$theta0-2*pi})
        -r[-2,-1] @{-3,w},1,1,1,3
        -cos[-1] -*[-1] $rho0 --lt[-1] 0 -abs[-2]
        -*[-1] {pi} -+[-3,-1] -%[-2] {2*pi}
        -*[-2] {0.5*@{-3,w}/pi} -*[-1] {@{-3,h}/$rhomax}
        -a[-2,-1] y
        -repeat {w} -point[-2] @{-1,($>,0)},@{-1,($>,1)},0,0.3,255 -done
        -rm[-1] -w1[-1]

      -elif {@{!1,x}>=0" && "@{!1,b}} # When clicking on the vote window.
        theta={@{!1,x}*2*pi/@{!1,w}}
        rho={@{!1,y}*$rhomax/@{!1,h}}
        x={@{-2,w}/2+$rho*cos($theta)}
        y={@{-2,h}/2+$rho*sin($theta)}
        x0={$x+1000*sin($theta)}
        y0={$y-1000*cos($theta)}
        x1={$x-1000*sin($theta)}
        y1={$y+1000*cos($theta)}
        [-2]
        -line[-1] $x0,$y0,$x1,$y1,1,0x0F0F0F0F,255
        -line[-1] {$x0+1},$y0,$x1,$y1,1,0x0F0F0F0F,255
        -line[-1] $x0,{$y0+1},$x1,$y1,1,0x0F0F0F0F,255
        -line[-1] $x0,$y0,$x1,$y1,1,0xF0F0F0F0,0
        -line[-1] {$x0+1},$y0,$x1,$y1,1,0xF0F0F0F0,0
        -line[-1] $x0,{$y0+1},$x1,$y1,1,0xF0F0F0F0,0
        -w[-1] -rm[-1]

      -elif {@{!,SPACE}" || "@{!1,SPACE}}
        -rm[-1] --b[-1] 1.5 -hough[-1] 512,400 -b[-1] 0.5 -+[-1] 1 -log[-1] -n[-1] 0,255
        -w1[-1] -1,-1,0,0,"Hough Transform"

      -elif @{!,r} -w[-2]
      -elif @{!1,r} -w1[-1]
      -endif

    -while {@!" && "@{!1}" && "!@{!,ESC}" && "!@{!,Q}" && "!@{!1,ESC}" && "!@{!1,Q}}

    -rm[-1] -endl
    -if {!@!" || "!@{!1}} -break -endif
    -w0 0
  -done -rm -v +

#@gmic x_jawbreaker : 0<_width<20,0<_height<20,0<_balls<=8
#@gmic : Launch the Jawbreaker game.
x_jawbreaker : -check "${1=12}>0 && $1<20 && ${2=13}>0 && $2<20 && ${3=5}>0 && $3<=8"
  -e[] "\n
------ Jawbreaker --------------------------------------------\n
----\n
---- The goal of the game is to remove the maximum number of\n
---- balls on the board, simply by clicking on them. But a\n
---- colored ball can disappear only if it is grouped with at\n
---- least one ball of the same color. The score is higher if\n
---- you destroy larger sets of connected colored balls.\n
----\n
---- Left mouse button to select/destroy balls on board.\n
---- Key 'BACKSPACE' or 'SPACE' to undo the last move.\n
---- Key 'S' to save snapshot of the current view.\n
---- Keys 'ESC' or 'Q' to exit.\n
----\n
--------------------------------------------------------------"
  -v -

  # Init images and variables.
  -i[board] $1,$2 -rand[board] 1,$3 -round[board] 1
  -i[undo] [-1]
  -i[balls] 32,32 -ball[-1] 255,255,255 -autocrop[-1] 0 -expand_xy[-1] 1,0 -*[-1] 1.5 -c[-1] 0,255 -r[-1] {@{board,w}*w},{@{board,h}*h},1,1,0,2 -/[-1] 255
  -i[back] {w},{h},1,3 -l[-1]
    -rand 0,255 -blur_xy 6,20 -equalize 100,0,255 -blur_xy 2,4
    -sh 0,0 -sh[-2] 1,1 -sh[-3] 2,2 -/[-3] 4 -/[-2] 8 -/[-1] 2 -rm[-3--1]
  -endl
  -i[visu] [back]
  score=0
  undoscore=0
  render_board=1
  shapescorey=0
  shapescore=0

  # Enter user-event loop.
  -do

    # Render board graphics.
    -if $render_board
     --abs[board] --[-1] 1 -*[-1] {360/$3} --t[board] 0 -*[-1] 0.9 -r[-2,-1] [balls] [balls] -a[-3--1] c -hsv2rgb[-1]
      --compose_channels[-1] + -t[-1] 0.1 -dilate[-1] 3
      -j[visu] [back] -j[visu] [-2],0,0,0,0,1,[-1] -rm[-2,-1]
      -if {!$shapescorey} -w[visu] @{back,w},@{back,h},0,0,"[G'MIC] Jawbreaker (score : "$score")" -endif
      render_board=0
    -endif

    # Add shape score sprite if necessary.
    -if $shapescorey
      --text[visu] "+"$shapescore,@{!,x},{@{!,y}-64+$shapescorey},32,{($shapescorey-1)/31},255
      shapescorey={max(0,$shapescorey-1)}
      -w[-1] @{back,w},@{back,h},0,0,"Jawbreaker (score : "$score")" -rm[-1] -wait 25
    -else -wait -endif

    # Check for the end of the game.
    --f[board] "if(i,i(x-1,y)==i || i(x+1,y)==i || i(x,y+1)==i || i(x,y-1)==i,0)"
    -if {!@{-1,+}} -rm[-1] -break -endif -rm[-1]

    # Manage user-events
    -if @{!,r} render_board=1                   # Will resize window to initial size, if resized.
    -elif @{!,S} -o[visu] gmic_jawbreaker.png   # Save snapshot if requested.
    -elif {@{!,BACKSPACE}" || "@{!,SPACE}}      # Manage undo move.
      -abs[undo] -j[board] [undo]
      score=$undoscore
      render_board=1

    -elif {@{!,x}">=0 && "@{!,b}}               # Manage button click.

      # Retrieve board coordinates.
      -wait -1
      x={"int("@{!,x}"*"@{board,w}"/"@{!,w}")"}
      y={"int("@{!,y}"*"@{board,h}"/"@{!,h}")"}

      # When selecting a ball -> display selection and init new shape score sprite.
      -if {@{board,($x,$y)}>0}
        -abs[board] -flood[board] $x,$y,0,0,0,1,-@{board,($x,$y)}
        --t[board] 0 --[-1] 1
        shapescore={(@{-1,+}+1)^2} shapescorey={if($shapescore,32,0)} -rm[-1]

      # When confirming selection of a ball -> remove set of connected balls.
      -elif @{board,($x,$y)}

        --flood[board] $x,$y,0,0,0,1,-1 -==[-1] -1
        -if {@{-1,+}>1} # If selected ball is connected to at least one ball.

          # Save undo state.
          -j[undo] [board]
          undoscore=$score

          # Manage board shifts (vertical and horizontal).
          -flood[board] $x,$y,0,0,0,1,0
          -repeat @{board,w}
            --columns[board] $> -mirror[-1] y
            h=@{board,h} -l[-1] -s -,0 -a y -if @# -r 1,$h,1,1,0 -mirror y -else -i 1,$h -endif -endl
            -j[board] [-1],$> -rm[-1]
          -done
          -lines[board] -1,100% -f[board] "if(y==0,if(i(x,h-1),x,w),i)" -sort[board] +,x -lines[board] 1,100%

          # Update score.
          score={$score+int((@{-1,+}-1)^2)}

        -endif
        -rm[-1] # Remove selection mask.

      -else -abs[board]  # Remove previous selection if clicked outside balls.
      -endif

      render_board=1
    -endif

  -while {@!" && "!@{!,Q}" && "!@{!,ESC}}

  # Game over.
  -if {@!" && "!@{!,ESC}}
    -w[] @{visu,w},@{visu,h},0,0,"[G'MIC] Jawbreaker (final score : "$score")"
    -i[gameover] 230,85 -text[-1] "Game Over !",3,0,57,1,1 -text[-1] "Score : "$score,24,54,32,1,1
    --dilate[-1] 5 -nm[-1] "mgameover" -*[-2] 255 -r[-2] 100%,100%,1,3
    -repeat 25
      --r[gameover,mgameover] {400-12*($>+1)}%,{400-12*($>+1)}%
      --j[visu] [-2],{(@{visu,w}-w)/2},{(@{visu,h}-h)/2},0,0,{$>/25},[-1]
      -w[-1] -rm[-3--1] -wait 25
    -done
    -do
      -wait -if @{!,r} -w[] @{!,w},@{!,h} -wait -1 -endif
      -while {@!" && "!@{!,Q}" && "!@{!,ESC}" && "!@{!,b}}
    -rm[gameover,mgameover]
  -endif

  # End properly.
  -rm[board,undo,balls,back,visu]
  -w 0 -v +

#@gmic x_life
#@gmic : Launch the game of life.
x_life :
  -e[] "\n
------ The game of life --------------------------------------\n
----\n
---- The goal is to create the biggest possible biological\n
---- system. You start with a stock of cells which you can\n
---- spread over the board. For each new cells created\n
---- simultaneously and spontaneously by your system, you\n
---- gain more new cells to scatter.\n
----\n
---- Left mouse button to scatter cells in stock.\n
---- Right mouse button to reset game.\n
---- Key 'S' to save snapshot of the current view.\n
---- Keys 'ESC' or 'Q' to exit.\n
----\n
--------------------------------------------------------------"
  -v -
  -i[0] 90,90,1,1,0                                             # Image[0] = game state.
  -i[1] [0] -f[1] 0                                             # Image[1] = generation counter.
  -i[2] 400,400,1,3                                             # Image[2] = visualization.
  -i[3] 1                                                       # Image[3] = colormap (to be initialized).
  iteration=0                                                   # Iteration counter.
  score=0                                                       # Current score.
  bestscore=0                                                   # Best score.
  stock=500                                                     # Remaining cells.
  -w[0] 400,400,0,0,"[G'MIC] The Game of Life"                  # Initialize display window.

  # Start user-event loop.
  -do
    (1,1,1;1,0,1;1,1,1) --correlate[0] [-1],0 -rm[-2]           # Count numbers of neighboring living cells.
    --t2[-1] 2,2 -and[-1] [0] -t2[-2] 3,3 -or[-2,-1]            # Make the game evolve (kill or create cells).
    -rv[0,-1]                                                   # Update game state.
    -if {@{!,x}>0" && "@{!,b}==1" && "$stock>0}                 # Add random cells to the game if user presses mouse button.
      nb={?*7}
      -repeat $nb
        x={@{!,x}/@{!,w}*@{0,w}+?(-4,4)}
        y={@{!,y}/@{!,h}*@{0,h}+?(-3,3)}
        -=[0] 1,$x,$y
        -=[1] $iteration,$x,$y
        -point[2] {$x*@{2,w}/@{0,w}},{$y*@{2,h}/@{0,h}},0,0.8,255
      -done
      stock={round(max(0,$stock-$nb))}
    -endif

    --[-1] [0] -*[-1] -1                                        # Compute difference between consecutive states.
    stock={$stock-2*(min(0,int(@{-1,+}/16*$score/150)))}        # Increment available cells if the evolution is fast.
    -+[1] [0]                                                   # Increment generation counter for still existing cells.
    -min[-1] 0 -+[-1] 1 -*[1,-1]                                # Reset generation counter for died cells.

    -if {@{!,b}==2}                                             # Reset game if right mouse button has been pressed.
      -f[0-2] 0 iteration=0 score=0 bestscore=0 stock=500 -rm[3] -i[3] 1
    -endif

    -if {@{3,w}==1}                                             # Create color palette if necessary.
      -rm[3] -i[3] {?(3,12)},1,1,3,?(100,255)
      -r[3] {?(100,300)}%,1,1,3,4
      -point[3] 0,0,0,1,0
      -r[3] {?(100,600)}%,1,1,3,5 -c[3] 0,255
    -endif

    --r[1] @{2,w},@{2,h} -and[-1] 7 -b[-1] {1+$score*0.05}   # Render colored image of the game and display it.
    -n[-1] 0,@{3,w} -map[-1] [3] -*[-1] 0.1 -+[2,-1] -/[2] 1.1
    [2] -if {@{!,x}>0}                                          # Add a small target icon at the mouse position.
      opac={0.7*min(1,$stock/500)} r={min(500,$stock)*cos($iteration)/100}
      -ellipse[-1] @{!,x},@{!,y},{15+$r},{15+$r},0,$opac,0,196,0
      -ellipse[-1] @{!,x},@{!,y},{10+$r},{10+$r},0,$opac,32,64,16
      -ellipse[-1] @{!,x},@{!,y},{5+$r},{5+$r},0,$opac,255,230,0
    -endif
    -text[-1] "Living cells : "$score"\n"\                      # Add score description.
              "Stock : "$stock"\n"\
              "Score : "$bestscore,5,3,22,0.7,255
    -w[-1] @{!,w},@{!,h}
    -if @{!,S} -o[-1] gmic_life.png -endif                      # Save snapshot if requested.
    -rm[-1]

    -if {!($iteration%10)} score=@{0,+} bestscore={max($score,$bestscore)} -endif  # Re-compute current and best scores, every 10th iterations.
    -wait 60
    iteration={$iteration+1}
  -while {@!" && "!@{!,ESC}" && "!@{!,Q}}

  # End game and quit properly.
  -rm[0-3] -w 0 -v +

#@gmic x_light
#@gmic : Launch the light demo.
x_light :
  -e[] "\n
------ Light demo ------------------------\n
----\n
---- Move light position with mouse.\n
---- Mouse buttons fade light in/out.\n
---- Keys 'ESC' or 'Q' to exit.\n
----\n
-----------------------------------------"
  -v -

  # Create warping and color images.
  1 -text[-1] "   G'MIC\nLight Demo",0,0,57,1,255 -expand_xy[-1] 15,0 -b[-1] 3
  [-1] -n[-2] 0,1 -r[-2] 100%,100%,1,3
  -sh[-2] 0,0 -*[-1] 120 -rm[-1]
  -sh[-2] 1,1 -*[-1] 70 -rm[-1]
  -sh[-2] 0,50%,0,2 -*[-1] 120 -rm[-1]
  25%,25%,1,1 -rand[-1] -20,20 -smooth[-1] 10,0,1,1,4 -r[-1] [-2],3 -b[-1] 3 -n[-1] -60,60
  -+[-2,-1] -g[-1] xy -a[-2,-1] c -n[-1] -150,150
  -w[] {2*@{-2,w}},{2*@{-2,h}},0,0,"[G'MIC] Light Demo"  # Init display window.

  # Create a large light image.
  light=70
  512,512 -gaussian[-1] $light -n[-1] 0,255
  t=0

  # Start animation.
  -do

    # Manage light position and intensity.
    -if {@{!,x}>=0}
      X={round((w-@{!,x})/2)}
      Y={round((h-@{!,y})/2)}
    -else
      X={round((w-@{-2,w}*(1+cos(2*$t)))/2)}
      Y={round((h-@{-2,h}*(1+sin(2.5*$t)))/2)}
      t={$t+0.02}
    -endif
    -if {@{!,b}&1} light={min(200,$light+10)} -gaussian[-1] $light -n[-1] 0,255 -endif
    -if {@{!,b}&2} light={max(10,$light-10)} -gaussian[-1] $light -n[-1] 0,255 -endif

    # Render lightened image.
    --z[-1] $X,$Y,{$X+@{-2,w}-1},{$Y+@{-2,h}-1}
    -warp[-1] [-3],1,0,1
    -r[-1] 100%,100%,1,3 -+[-1] [-4] -c[-1] 0,255
    -w[-1] {2*w},{2*h}
    -rm[-1] -if {@{!,x}>=0" && "!@{!,b}} -wait -else -wait 20 -endif
  -while {@!" && "!@{!,ESC}" && "!@{!,Q}}
  -w[] 0 -rm[-3--1] -v +

#@gmic x_mandelbrot : _julia={ 0 | 1 },_c0r,_c0i
#@gmic : Launch Mandelbrot/Julia explorer.
x_mandelbrot : -skip ${1=0},${2=0.317},${3=0.03}
  -e[] "\n
------ Mandelbrot/Julia explorer -----------------\n
----\n
---- Select zooming region with mouse.\n
---- Click once to reset zoom factor.\n
---- Keys 'ESC' or 'Q' to exit.\n
---- Key 'C' to print current fractal coordinates.\n
----\n
--------------------------------------------------"

  # Init variables and display.
  -v -
  -rm -w 512,512,0,0 -_x_mandelbrot_coords $1 -_x_mandelbrot_palette

  # Start event loop.
  -do
    siz={min(@{!,w},@{!,h})}                                                                      # Desired window dimension.
    $siz,$siz -mandelbrot[-1] @0,256,$1,{if($1,$2,0)},{if($1,$3,0)} -map[-1] [1]                  # Render fractal.
    -if $1 -w[-1] $siz,$siz,0,0,"[G'MIC] Julia set c=("@{0,0}","@{0,1}")-("@{0,2}","@{0,3}"), c0=($2,$3)" # Display on window.
    -else -w[-1] $siz,$siz,0,0,"[G'MIC] Mandelbrot set c=("@{0,0}","@{0,1}")-("@{0,2}","@{0,3}")" -endif
    w={w} h={h} -select[-1] 2                                                                     # Get the user selection.

    -if {@{-1,0}>0}                                                                               # If valid selection found.
      M={max(@{-1,3}-@{-1,0},@{-1,4}-@{-1,1})}                                                    # Compute max dimension of selected rectangle.
      -if {$M<5} -_x_mandelbrot_coords $1 -rm[1] -_x_mandelbrot_palette -mv[-1] 1                 # If selection too small, reset the view,
      -else ({@{0,0}+@{-1,0}*(@{0,2}-@{0,0})/$w};\                                                # Else compute new fractal coordinates.
             {@{0,1}+@{-1,1}*(@{0,3}-@{0,1})/$h};\
             {@{0,0}+(@{-1,0}+$M)*(@{0,2}-@{0,0})/$w};\
             {@{0,1}+(@{-1,1}+$M)*(@{0,3}-@{0,1})/$h})
      -endif
      -rm[0] -mv[-1] 0                                                          # Validate new coordinates.
    -endif
    -rm[-1]                                                                     # Delete latest rendering.
    -if {@{!,C}}                                                                # If 'C' key has been pressed.
      -if $1 -v + -e[0--4] "Julia set, at c = ("@{0,0-1}")-("@{0,2-3}"), with c0 = ($2,$3)." -v -
      -else -v + -e[0--4] "Mandelbrot set, at c = ("@{0,0-1}")-("@{0,2-3}")." -v -
      -endif
    -endif
    -if {!@!" || "@{!,ESC}" || "@{!,Q}} -rm -w 0 -v + -return -endif
    -wait -1
  -while 1

_x_mandelbrot_coords :
  -if $1 (-2;-2;2;2) -else (-2.1;-1.5;1.2;1.5) -endif

_x_mandelbrot_palette :
  6,1,1,3 -rand[-1] 20,255 -r[-1] 32,1,1,3,3 -r[-1] 1024,1,1,3,0,2 -=[-1] 0,0,0,0,0 -=[-1] 0,0,0,0,1 -=[-1] 0,0,0,0,2

#@gmic x_minesweeper : 8<=_width=<20,8<=_height<=20
#@gmic : Launch the Minesweeper game.
x_minesweeper : -check "${1=20}>=8 && $1<=30 && ${2=20}>=8 && $2<=30"
  -e[] "\n
------ Minesweeper -------------------------------------------\n
----\n
---- The goal is to clear the minefield without detonating a\n
---- mine.\n
----\n
---- Left mouse button to try clearing one square.\n
---- Right mouse button to flag or unflag a square.\n
---- Middle mouse button to reset mine field.\n
---- Keys 'ESC' or 'Q' to exit.\n
----\n
--------------------------------------------------------------"
  -v -
  # Generate random mine field and player board.
  # Labels : 0=mine, 1=empty, 2='1-near', 3='2-near', ..., 9='8-near', 10=still unknown.
  $1,$2 -noise[-1] 30,2 nb_mines=@{-1,+} (1,1,1;1,0,1;1,1,1) --convolve[-2] [-1],0 -rm[-2] -+[-1] 1 -==[-2] 0 -*[-2,-1] -nm[-1] field
  --f[field] 11 -nm[-1] board

  # Generate sprite graphics.
  24,24,1,3,200 -fc[-1] 255,180,130
  -ellipse[-1] 12,12,4,4 -line[-1] 6,12,18,12 -line[-1] 12,6,12,18 -line[-1] 13,10,14,10,1,255 -line[-1] 13,11,14,11,1,255
  -z[-1] 1,1,{w-2},{h-2} -frame[-1] 1,1,0
  --fc[-1] 230,250,255
  --text[-1] "1",10,5,13,1,0,196,0 --text[-2] "2",9,5,13,1,0,128,0 --text[-3] "3",9,5,13,1,0,0,255
  --text[-4] "4",9,5,13,1,255,0,0 --text[-5] "5",9,5,13,1,200,0,0 --text[-6] "6",9,5,13,1,150,0,0
  --text[-7] "7",9,5,13,1,128,0,0 --text[-8] "8",9,5,13,1,64,0,0 -erode[-8--1] 2
  --f[-1] 'if(x<=1||y<=1||x>=w-2||y>=h-2,if(x<y,128,255),160+2*(y+x))'
  --polygon[-1] 4,13,15,11,15,6,18,17,18,1,0 -line[-1] 12,15,12,6,1,255,0,0 -polygon[-1] 3,12,6,6,9,12,12,1,220,0,0
  -rv[-2,-1] -a[-12--1] x -nm[-1] sprites

  # Pre-calculate offsets and canvas for faster board rendering.
  (0,23;0,23^0,0;23,23) -r[-1] 24,24,1,2,3 -r[-1] {@{board,w}*24},{@{board,h}*24},1,2,0,2 -nm[-1] offsets
  [-1],[-1],1,3,255 -frame[-1] 1,1,0 -frame[-1] 23,23,255
  0 -text[-1] "Number of mines : "$nb_mines,0,0,18,1,100,200,255 -negative[-1] -j[-2] [-1],{(@{-2,w}-w)/2},{@{-2,h}-h-2} -rm[-1]
  -nm[-1] canvas

  # Start user interaction loop.
  failed=0 succeeded=0 tic=@| nb_flags=0
  -do

    # Render board.
    --*[board] 24 -r[-1] [offsets],[offsets] -channels[-1] 0,1 -+[-1] [offsets] --warp[sprites] [-1],0,0 -rm[-2]
    -j[canvas] [-1],24,24 -rm[-1]

    # Wait for user's selection.
    -wait -1
    -if $failed
      0 -text[-1] "Game\nOver !",3,3,38,1,255 -r[-1] 100%,100%,1,4 -sh[-1] 3,3 -dilate[-1] 5 -/[-1] 2 -rm[-1]
      -drop_shadow[-1] 5,5,1 -compose_alpha[canvas,-1]
      0 -text[-1] "Boom ! You failed !",0,0,18,1,100,255,255 -r[-1] @{canvas,w},100%,1,3,0,0,0.5,0.5 -negative[-1] -j[canvas] [-1],0,3 -rm[-1]
      -do -w[canvas] {w},{h} -wait -while {@!" && "!@{!,ESC}" && "!@{!,Q}}
    -elif $succeeded
      0 -text[-1] "Success !",3,3,38,1,255 -r[-1] 100%,100%,1,4 -sh[-1] 3,3 -dilate[-1] 5 -/[-1] 2 -rm[-1]
      -drop_shadow[-1] 5,5,1 -compose_alpha[canvas,-1]
      0 -text[-1] "Congratulations ! ("{round(@|-$tic)}" s)",0,0,18,1,255,100,255 -r[-1] @{canvas,w},100%,1,3,0,0,0.5,0.5
      -negative[-1] -j[canvas] [-1],0,3 -rm[-1]
      -do -w[canvas] {w},{h} -wait -while {@!" && "!@{!,ESC}" && "!@{!,Q}}
    -else
      -do
        0 -text[-1] "Elapsed time : "{round(@|-$tic)}" s / Flags : "$nb_flags,0,0,18,1,255,200,0 -r[-1] @{canvas,w},100%,1,3,0,0,0.5,0.5
        -negative[-1] -j[canvas] [-1],0,3 -rm[-1]
        -wait 50
        x={int((@{!,x}-24)/24)} y={int((@{!,y}-24)/24)} b=@{!,b}
        -w[canvas] {w},{h},0,0,"[G'MIC] Minesweeper"
      -while {@!" && "!@{!,ESC}" && "!@{!,Q}" && "!$b}
    -endif

    # Manage selected square.
    -if {$x>=0\ &&\ $y>=0\ &&\ $x<@{board,w}\ &&\ $y<@{board,h}}
      -if {$b&1}  # Try to clean square.
        val=@{field,($x,$y)}
        -if {$val==0} --==[field] 0 -j[board] [field],0,0,0,0,1,[-1] -rm[-1] failed=1  # Found a mine -> boom !
        -elif {$val==1} --flood[field] $x,$y,0,0,1,1,-1 -==[-1] -1 -dilate[-1] 3 -j[board] [field],0,0,0,0,1,[-1] -rm[-1] # Found an empty area.
        -else -=[board] $val,$x,$y # Close to one or several mines.
        -endif
      -elif {$b&2} -=[board] {if(@{board,($x,$y)}==11,10,11)},$x,$y nb_flags={$nb_flags+if(@{board,($x,$y)}==11,-1,1)} # Flag or unflag a square.
      -elif {$b&4} -f[board] 10  # Reset minefield.
      -endif
    -endif

    -if {$nb_mines==$nb_flags\ &&\ @{board,M}!=11} succeeded=1 -endif  # Check if board is cleared.
  -while {@!" && "!@{!,ESC}" && "!@{!,Q}}
  -w 0 -v +

#@gmic x_minimal_path
#@gmic : Launch the minimal path demo.
x_minimal_path :
  -e[] "\n
------ Minimal path demo -------------------------------------\n
----\n
---- Click on two points to compute and display the minimal\n
---- path between those points. The ending point is then\n
---- chosen as the next starting point for another path.\n
---- Key 'S' to save snapshot of the current view.\n
---- Keys 'ESC' or 'Q' to exit.\n
----\n
--------------------------------------------------------------"
  -v -
  -if {!@#} -testimage2d 400 -endif
  -n 0,200 -repeat @# -l[$>]
    -w[0] -1,-1,0,0,"[G'MIC] Select starting point P0"
    --gradient_norm -b[-1] 1 -f[-1] exp(-i/10)
    -to_rgb[0] --select[0] 0 P0=@-1
    -ellipse[0] @{-1,0,1},3,3,0,1,255,0,255
    -ellipse[0] @{-1,0,1},3,3,0,1,0xFFFFFFFF,255,255,255
    -rm[-1]
    -if {min($P0)>=0}
      p=1
      -do
        -w[0] -1,-1,0,0,"[G'MIC] Select ending point P"$p
        --select[0] 0
        -if {@{!,S}}
          -rm[-1]
          --text_outline[0] "Saving snapshot...",5,5,13,1,1,255,255,255 -w[-1] -rm[-1]
          -o[0] gmic_minimal_path.png
          -wait -1
        -else
          P1=@-1
          -ellipse[0] @{-1,0,1},3,3,0,1,255,0,255
          -ellipse[0] @{-1,0,1},3,3,0,1,0xFFFFFFFF,255,255,255
          -rm[-1]
          -if {min($P1)>=0}
            --text_outline[0] "Processing...",5,5,13,1,1,255,255,255 -w[-1] -rm[-1]
            --minimal_path[1] $P0,$P1
            -pointcloud[-1] 0 -*[-1] 255 -r[-1] 100%,100%,1,[0],0,0,0,0,0,0.5 -r[-1] [0],0 -or[0,-1]
            P0=$P1 p={$p+1}
          -endif
        -endif
      -while {@!" && "!@{!,ESC}" && "!@{!,Q}}
    -endif
    -rm[1]
  -endl -done -w 0 -v +

#@gmic x_paint
#@gmic : Launch the interactive painter.
x_paint :
  -e[] "\n
------ Interactive painter -----------------------\n
----\n
---- Use mouse to select color and brush.\n
---- Left button draws a colored stroke.\n
---- Right button fills a colored region.\n
---- Arrow keys or SPACE and BACKSPACE to swap\n
---- between available images.\n
---- Key 'S' to save snapshot of the current view.\n
---- Keys 'ESC' or 'Q' to exit.\n
----\n
--------------------------------------------------"
  -v - -to_rgb

  # Init variables and images.
  -if {!@#} -i[0] 512,512,1,3,255 -nm[0] "New image" -endif
  color=0,0,0
  saturation=1
  brushsize=3
  brushopacity=0
  brushangle=90
  brushthickness=1
  image=0
  refresh_palette=1
  refresh_image=1
  refresh_brush=1
  ox1=-1
  oy1=-1
  1 1    # Palette image [-2] and brush image [-1]

  # Start user event loop.
  -do

    # Open/refresh palette window.
    -if $refresh_palette
      -rm[-2] (0,359;0,359^$saturation,$saturation;$saturation,$saturation^1,1;0,0) -r[-1] 256,64,1,3,3 -hsv2rgb[-1]
      (255;0) -r[-1] 16,@{-2,h},1,3,3 -line[-1] 0,0,0,100%,1,0 -a[-2,-1] x
      {w},16,1,3 -text[-1] "Selected color",4,2,13,1,255
      -polygon[-1] 4,80,3,100,3,100,13,80,13,1,$color
      -polygon[-1] 4,80,3,100,3,100,13,80,13,1,0xFFFFFFFF,255,255,255
      -a[-2,-1] y -w2[-1] {w},{h},0,0,"Palette" -mv[-1] -2
      refresh_palette=0
    -endif

    # Open/refresh brush window.
    -if $refresh_brush
      -rm[-1] (32,64;64,32) -r[-1] 16,16,1,3,1 -r[-1] {8*48},{4*48},1,3,0,2
      -repeat 4 -repeat 8
        -ellipse[-1] {48*$>+24},{48*@{>,-2}+24},{2*$>+1},{(2*$>+1)*$brushthickness},$brushangle,{1-@{>,-2}/4},255
      -done -done
      -polygon[-1] 4,{$brushsize*48},{$brushopacity*48},\
                     {$brushsize*48+47},{$brushopacity*48},\
                     {$brushsize*48+47},{$brushopacity*48+47},\
                     {$brushsize*48},{$brushopacity*48+47},\
                     1,0xFFFFFFFF,255,128,128
      {w},16,1,3 -line[-1] 0,50%,100%,50%,1,0x55555555,128,64,128
      bx={$brushangle*w/180}
      -polygon[-1] 4,{$bx-16},20%,{$bx+16},20%,{$bx+16},80%,{$bx-16},80%,1,128
      -line[-1] {$bx-16},20%,{$bx+16},20%,1,255 -line[-1] {$bx+16},20%,{$bx+16},80%,1,255
      -line[-1] {$bx-16},80%,{$bx+16},80%,1,64 -line[-1] {$bx-16},20%,{$bx-16},80%,1,64
      -a[-2,-1] y
      16,{h-16},1,3 -line[-1] 50%,0,50%,100%,1,0x55555555,128,64,128
      by={$brushthickness*(h-16)}
      -polygon[-1] 4,20%,{$by-16},80%,{$by-16},80%,{$by+16},20%,{$by+16},1,128
      -line[-1] 20%,{$by-16},80%,{$by-16},1,255 -line[-1] 80%,{$by-16},80%,{$by+16},1,255
      -line[-1] 20%,{$by-16},20%,{$by+16},1,64 -line[-1] 20%,{$by+16},80%,{$by+16},1,64
      -a[-2,-1] x
      -w3[-1] {w},{h},0,0,"Brush"
      refresh_brush=0
    -endif

    # Open/refresh image window.
    -if $refresh_image
      -w1[$image] @{$image,w},@{$image,h},0,0,"Image "#$image" : "@{$image,b}.@{$image,x}
      refresh_image=0
    -endif

    # Manage user events.
    x1=@{!1,x} y1=@{!1,y}
    x2=@{!2,x} y2=@{!2,y}
    x3=@{!3,x} y3=@{!3,y}

    -if {$x1>=0}                        # Event in the image window.
      -if {@{!1,b}&1}                   # Left button -> draw brush stroke.
        ox1={if($ox1<0,$x1,$ox1)}
        oy1={if($oy1<0,$y1,$oy1)}
        delta={max(abs($x1-$ox1),abs($y1-$oy1))}
        r1={2*$brushsize+1}
        r2={$r1*$brushthickness}
        dx={2*($x1-$ox1)/max(1,$delta)}
        dy={2*($y1-$oy1)/max(1,$delta)}
        o={1-($brushopacity/4)^0.04}
        -repeat {max(1,($delta+1)/2)}
          -ellipse[$image] {$ox1+$>*$dx},{$oy1+$>*$dy},$r1,$r2,$brushangle,$o,$color
        -done
        ox1=$x1 oy1=$y1
        refresh_image=1
      -else
        ox1=-1 oy1=-1
        -if {@{!1,b}&2}               # Right button -> fill region.
          -flood[$image] $x1,$y1,0,10,0,1,$color
          refresh_image=1
        -endif
      -endif
    -endif

    -if {@{!1,ARROWRIGHT}" || "@{!2,ARROWRIGHT}" || "@{!3,ARROWRIGHT}" || "\  # Manage image selection.
         @{!1,ARROWUP}" || "@{!2,ARROWUP}" || "@{!3,ARROWUP}" || "\
         @{!1,SPACE}" || "@{!2,SPACE}" || "@{!3,SPACE}}
      image={($image+1)%(@#-2)} refresh_image=1
    -elif {@{!1,ARROWLEFT}" || "@{!2,ARROWLEFT}" || "@{!3,ARROWLEFT}" || "\
           @{!1,ARROWDOWN}" || "@{!2,ARROWDOWN}" || "@{!3,ARROWDOWN}" || "\
           @{!1,BACKSPACE}" || "@{!2,BACKSPACE}" || "@{!3,BACKSPACE}}
      image={($image-1)%(@#-2)} refresh_image=1
    -endif

    -if @{!1,S} -o[$image] gmic_paint.png -endif  # Save snapshot if requested.

    -if {@{!2,b}" && "$x2>=0" && "$y2<64}  # Manage color selection from the palette window.
      -if {$x2>=256} saturation={1-$y2/63}
      -elif {$x2>=0} color=@{-2,($x2,$y2,0,0)},@{-2,($x2,$y2,0,1)},@{-2,($x2,$y2,0,2)}
      -endif
      refresh_palette=1
    -endif

    -if {@{!3,b}" && "$x3>=0}  # Manage brush selection.
      -if {$x3<384" && "$y3>=192}   # Bottom slider -> select brush angle.
        brushangle={$x3*180/(@{-1,w}-16)}
      -elif {$x3>=384" && "$y3<192} # Right slider -> select brush thickness.
        brushthickness={$y3/(@{-1,h}-16)}
      -elif {$x3<384" && "$y3<192}
        brushsize={int($x3*8/(@{-1,w}-16))}
        brushopacity={int($y3*4/(@{-1,h}-16))}
      -endif
      refresh_brush=1
    -endif
    -wait
    -while {@{!1}" && "!@{!1,Q}" && "!@{!1,ESC}}

  # Exit properly.
  -w1[] 0 -w2[] 0 -w3[] 0 -rm[-2,-1] -v +

#@gmic x_plasma
#@gmic : Launch the plasma demo.
x_plasma :
  -e[] "\n
------ Plasma demo ----------------------\n
----\n
---- Keys 'ESC' or 'Q' to exit.\n
----\n
-----------------------------------------"
  -v -

  # Init plasma backgrounds.
  N=8
  -repeat $N
    256,150,1,3 -rand[-1] 0,255 -plasma[-1] 1,0,7 -n[-1] 0,255
    amp={?(-40,40)} freq={round(?(2,6))} dir$>={if(?<0.5,-1,1)*round(?(1,2))}
    100%,100%,1,1,'$amp*cos(y*2*pi*$freq/h)'
  -done

  {w+2},100%,1,1,'x' 100%,100%,1,1,'Y=(y-60+5*cos(x/30)+10*sin(x/15));if(Y<0||Y>=32,-1,Y)' -a[-2,-1] c
  0 -text[-1] "** Welcome to G'MIC, a powerful image processing framework **",0,0,32,1,255
  -b[-1] 0.6 -n[-1] 0,255
  M={w}

  # Start animation loop.
  -w[] {2*@{0,w}},{2*@{0,h}},0,0,"[G'MIC] Plasma demo"
  t=0 tt={-1.5*@{0,w}}
  -do
    tic=@|

    # Render interpolated background between two successive plasmas.
    a={int($t)}   a2={2*$a} a21={$a2+1}
    b={($a+1)%$N} b2={2*$b} b21={$b2+1}
    --warp[$a2] [$a21],1,0,2
    --warp[$b2] [$b21],1,0,2
    -j[-2] [-1],0,0,0,0,{$t-$a} -rm[-1]

    -shift[$a21] 0,${dir$a},0,0,2  # Animate plasma background.
    -shift[$b21] 0,${dir$b},0,0,2
    -if {int($t+0.005)>int($t)} dir$a={if(?<0.5,-1,1)*round(?(1,3))} -endif
    t={($t+(@|-$tic))%$N}

    # Render text scrolling.
    --z[-2] $tt,{$tt+w-1+2}
    -warp[-1] [-4],0,0,0
    -r[-1] 100%,100%,1,3
    --*[-1] -1 -+[-1] 255
    -j[-3] [-1],0,0,0,0,1,[-2],255 -rm[-1]
    -j[-2] [-1],-2,-2,0,0,1,[-1],255 -rm[-1]

    tt={$tt+(@|-$tic)*100} # Animate scrolling.
    -if {$tt>=$M} tt={-1.5*@{0,w}} -endif

    # Display rendered frame.
    -w[-1] -rm[-1]
    -wait 20
  -while {@!" && "!@{!,ESC}" && "!@{!,Q}}
  -rm[{-2*$N-2}--1] -w[] 0 -v +

#@gmic x_reflection3d
#@gmic : Launch the 3d reflection demo.
x_reflection3d :
  -e[] "\n
------ 3d reflection demo ---------------\n
----\n
---- Keys 'ESC' or 'Q' to exit.\n
----\n
-----------------------------------------"
  -v -

  # Render background.
  128,256,1,3 -rand[-1] 0,255 -plasma[-1] 1,100 -blur_xy[-1] 30,2
  -sh[-1] 0,0 -n[-1] 0,90 -rm[-1] -sh[-1] 1,1 -n[-1] 0,60 -rm[-1] -sh[-1] 2,2 -n[-1] 0,180 -rm[-1]
  --mirror[-1] x [-2,-1] -a[-4--1] x
  --luminance[-1] -mirror[-1] x -b[-1] 2 -n[-1] 0,255

  # Create 3d objects.
  -torus3d 30,10 -col3d[-1] 255,200,0
  -spherical3d 47,34,"80+20*abs(cos(2*theta))" -s3d[-1] -rm[-2] -i[-2] 3,{h},1,1,150,220,255,200,255,255 -y[-2] y -a[-6--1] y
  -spherical3d 47,34,"100*abs(1+0.6*cos(3*phi)*sin(4*theta))"
  -r3d[-2,-1] 0,1,0,90 -db3d 0

  # Start animation loop.
  xb=0 xl=0 anim=0
  -w[] 400,400,0,0,"[G'MIC] 3d reflection demo"
  -do

    tic=@|
    # Recreate 3d interpolated background object.
    --lines[-1] 8,{8+3*i(0,6)-1} --j[-3] [-1],0,8,0,0,{if($anim<250,0,0.5-0.5*cos(($anim-250)/100))} -rm[-2]

    # Render 3d background object (with flat colors).
    --z[-6] $xb,0,{$xb+255},255 -m3d 3 -object3d[-1] [-2],75%,50%,0,1,0

    # Render light reflection map.
    --z[-6] $xl,0,{$xl+255},255
    xf={min(30,$anim-70)+20*cos(1.8*@|)}
    yf={50+20*sin(2.7*@|)}
    -m3d 4 -object3d[-1] [-6],{20+$xf}%,$yf%,0,1,0

    # Add light reflection to 3d background object.
    -l3d [-1] -rm[-1] -m3d 5 --object3d[-1] [-2],75%,50%,0,1,0 -j[-2] [-1],0,0,0,0,0.6 -rm[-3,-1]

    # Add 3d foreground object.
    -m3d 4 -object3d[-1] [-4],$xf%,$yf%,0,1,0

    # Display frame and update animation variables.
    -w[-1] -rm[-1]
    xb={($xb+6)&255}
    xl={($xl-6)&255}
    anim={$anim+1}
    -r3d[-2,-1] {sin(0.5*@|)},{cos(@|)},1,{(@|-$tic)*33}
    -r3d[-3] -1,0.3,0.8,{(@|-$tic)*100}
    -wait 20
  -while {@!" && "!@{!,ESC}" && "!@{!,Q}}
  -rm[-5--1] -w[] 0 -v +

#@gmic x_rubber3d
#@gmic : Launch the 3d rubber demo.
x_rubber3d :
  -e[] "\n
------ 3d rubber demo -------------------\n
----\n
---- Keys 'ESC' or 'Q' to exit.\n
----\n
-----------------------------------------"
  -v - -rm
  -sphere3d 150,0 -torus3d 70,15 -cylinder3d 20,40
  -col3d[-3] 200,200,200,0.3 -col3d[-2] 128,200,76 -col3d[-1] 200,128,76
  -c3d[-3--1] -r3d[-1] 1,0,0,70 -+3d[-3--1] -+3d[-1] 10,-8,20 -db3d 0 -m3d 3
  256,256,64,3
  {w},{h},1,3,'if(c==0,x,if(c==1,y,y*@{1,d}/h))'
  {w},{h},1,3
  frame=0
  -do
    {w},{h},1,3 -fc[-1] 16,32,32 -object3d[-1] [0],50%,50%,0,1,0 -j[1] [-1],0,0,$frame -rm[-1]
    -r3d[0] 0.1,1,0.6,{3*cos(@|*1.25)} -r3d[0] 1,0.2,0.6,-1
    --warp[1] [2],0,0 -*[3] 0.8 -*[-1] 0.2 -+[3,-1]
    -w[-1] {1.2*w},{1.2*h},0,0,"Rubber 3d" -wait 20
    -sh[2] 2,2 --[-1] 1 -and[-1] {@{1,d}-1} -rm[-1]
    frame={($frame-1)%@{1,d}}
  -while {@!" && "!@{!,ESC}" && "!@{!,Q}}
  -rm -w 0 -v +

#@gmic x_shadebobs
#@gmic : Launch the shade bobs demo.
x_shadebobs :
  -e[] "\n
------ Shade bobs demo --------------------------\n
----\n
---- Keys 'ESC' or 'Q' to exit.\n
----\n
-------------------------------------------------"
  -v -

  # Initialize variables and images.
  -rm t=100 rx=0 ry=0 rz=0 rt=0 rcx=0 nbbobs=0 rybobs=0
  -w 512,512,0,0,"[G'MIC] Shade bobs"
  1 {0.75*@{!,w}},{0.75*@{!,h}}

  # Start animation loop.
  -do
    t={$t+0.015}
    -if {$t>4*pi" || "@{!,b}} # Reset variables if necessary.
      -f[-1] 0
      rx={?(-1,1)} ry={?(-1,1)} rz={?(-1,1)} rt={?(-1,1)} rcx={?(-0.6*0.6)} t=0
      nbbobs={20+round(?(80))} rybobs={(10+round(?(50)))*min(w,h)/300}
      -rm[0] -i[0] {4+round(?(12))},1,1,3 -noise[0] 255,2 -r[0] 256,1,1,3,3 -*[0] 255 -shift[0] 1 -wait -1
    -endif

    -repeat $nbbobs # Draw ellipses
      r={$ry+$rx*cos(6*$rz*$t)+(1-$rx)*sin(6*$rt*$t)}
      a={(360*sin($rz*$t)+30*$ry*$>)*pi/180}
      ax={2*$>*pi/$nbbobs+$t}
      cx={(1+$rcx*cos($ax)+$r*cos($a))*w/2}
      cy={(1+$rcx*sin($ax)+$r*sin($a))*h/2}
      -ellipse[-1] $cx,$cy,$rybobs,$rybobs,0,-1,1
    -done

    -and[-1] 255 --map[-1] [0] -w[-1] -rm[-1] -wait 20   # Map colors and display.
  -while {@!" && "!@{!,ESC}" && "!@{!,Q}}
  -rm -w 0 -v +

#@gmic x_spline
#@gmic : Launch spline curve editor.
x_spline :
  -e[] "\n
------ Spline curve editor --------------------------\n
----\n
---- Mouse to insert/move/delete points.\n
---- Key 'R' to reset the curve.\n
---- Key 'SPACE' to shows/hide spline curve.\n
---- Key 'P' to shows/hide control points.\n
---- Key 'ENTER' to shows/hide control polygon.\n
---- Key 'T' to shows/hide point tangents.\n
---- Key 'I' to shows/hide point indices.\n
---- Key 'C' to shows/hide point coordinates.\n
---- Keys '+' and '-' to increase/decrease roundness.\n
---- Keys 'ESC' or 'Q' to exit.\n
----\n
-----------------------------------------------------"

  # Init display and variables.
  -v -
  -if @# -a x -n 0,255 -to_rgb -else (0;0^0;128^0;0) -r[-1] 512,512,1,3,3 -name[-1] "[G'MIC] Spline Editor" -endif
  -w[0] @{0,w},@{0,h},0,0,@{-1,n} -r[0] @{!,w},@{!,h},1,3,1
  -i[1] 1        # Point coordinates
  roundness=0.5  # Curve roundness
  visuflags=23   # Visualisation flags
  nearest=-1     # Nearest point
  active=-1      # Active point

  # Start event loop.
  -do

    # Init coordinates [1] if necessary.
    -if {@{1,#}==1}
      -rm[1] roundness=0.5 nearest=-1 active=-1
      -i[1] ({0.2*w},{0.2*h};\
             {0.2*w},{0.8*h};\
             {0.8*w},{0.8*h};\
             {0.8*w},{0.2*h})
    -endif

    # Estimate screen-normalized coordinates [2], curve tangents [3] and tangent orientations [4].
    [1] ({@{!,w}/@{0,w}},{@{!,h}/@{0,h}}) -*[-2,-1]                        # Normalized coordinates.
    --shift[2] 0,-1,0,0,2 --shift[2] 0,1,0,0,2 --[-2,-1] -*[-1] $roundness # Curve tangents.
    --s[-1] x -sqr[-2,-1] -+[-2,-1] -sqrt[-1] -r[-1] 2 --/[-2,-1] -rm[-2]  # Tangent orientations.

    # Display curve, control points, polygon and tangents.
    --r[0] @{!,w},@{!,h},1,3
    -if {$visuflags&4} -polygon[-1] @{2,h},@2,0.3,128,200,255 -endif
    -repeat @{1,h}
      -line[-1] @{2,0-3},0.3,255,255,0
      -if {$visuflags&1} -spline[-1] @{2,0-1},@{3,0-1},@{2,2-3},@{3,2-3},1,255 -endif
      -if {$visuflags&8} -line[-1] {@{2,0}-@{4,0}*20},{@{2,1}-@{4,1}*20},{@{2,0}+@{4,0}*20},{@{2,1}+@{4,1}*20},1,0,255,0 -endif
      -if {$visuflags&16} -text[-1] $>,{@{2,0}-3},{@{2,1}-18},13,1,255,255,0 -endif
      -if {$visuflags&32} -text[-1] "("{round(@{1,0})}","{round(@{1,1})}")",{@{2,0}-16},{@{2,1}+10},13,1,100,200,255 -endif
      -shift[1-4] 0,-1,0,0,2
    -done
    -if {$visuflags"&2"} -repeat @{1,h}
      -ellipse[-1] @{2,0-1},4,4,0,1,0,0,0 -ellipse[-1] @{2,0-1},2,2,0,1,255,100,155 -shift[2] 0,1,0,0,2
    -done -endif
    -w[-1] -rm[3,4,-1] -wait

    # Handle key events.
    -if @{!,SPACE} visuflags={$visuflags+if($visuflags&1,-1,1)} -wait -1 -endif  # Show/hide spline.
    -if @{!,P} visuflags={$visuflags+if($visuflags&2,-2,2)} -wait -1 -endif      # Show/hide points.
    -if @{!,ENTER} visuflags={$visuflags+if($visuflags&4,-4,4)} -wait -1 -endif  # Show/hide polygon.
    -if @{!,T} visuflags={$visuflags+if($visuflags&8,-8,8)} -wait -1 -endif      # Show/hide tangents.
    -if @{!,I} visuflags={$visuflags+if($visuflags&16,-16,16)} -wait -1 -endif   # Show/hide indices.
    -if {@{!,C}" && "!@{!,CTRLLEFT}" && "!@{!,CTRLRIGHT}} visuflags={$visuflags+if($visuflags&32,-32,32)} -wait -1 -endif # Show/hide coordinates.
    -if {@{!,PADADD}" && "$roundness<1} roundness={$roundness*1.1} -wait -1 -endif    # Increase roundness.
    -if {@{!,PADSUB}" && "$roundness>0.1} roundness={$roundness*0.9} -wait -1 -endif  # Decrease roundness.
    -if {@{!,R}" && "!@{!,CTRLLEFT}" && "!@{!,CTRLRIGHT}} -rm[-1] -i[1] 1 -wait -1 -endif # Reset curve.
    -if {(@{!,CTRLLEFT}" || "@{!,CTRLRIGHT})" && "@{!,D}} -w[] {@{!,w}*1.5},{@{!,h}*1.5} -endif # Increase window size.
    -if {(@{!,CTRLLEFT}" || "@{!,CTRLRIGHT})" && "@{!,C}} -w[] {@{!,w}/1.5},{@{!,h}/1.5} -endif # Decrease window size.
    -if {(@{!,CTRLLEFT}" || "@{!,CTRLRIGHT})" && "@{!,R}} -w[] @{0,w},@{0,h} -endif             # Reset window size.
    -if @{!,r} -w[] -endif # Resize window if necessary.

    # Set/unset active point.
    -if {@{!,b}==0} active=-1                                   # Unset active point if mouse button is released.
    -elif {@{!,x}>=0" && "@{!,b}" && "$active==-1}              # Find new active point.
      [2] (@{!,x},@{!,y}) --[-2,-1] -sqr[-1] -s[-1] x -+[-2,-1] # Compute distance vector to points.
      (@{-1,c}) nearest=@{-1,1} -rm[-1]                         # Set nearest point.
      -if {@{-1,m}<64} active=$nearest -endif                   # Set it as active point, if near enough.
      -rm[-1]
    -endif
    -rm[2]

    # Move active point.
    -if {@{!,b}&1" && "@{!,x}>=0" && "$active!=-1}
      -=[1] {@{!,x}*@{0,w}/@{!,w}},0,$active
      -=[1] {@{!,y}*@{0,h}/@{!,h}},1,$active

    # Delete nearest point.
    -elif {@{!,b}&2" && "@{!,x}>=0" && "@{1,h}>3}
      -l[1] -s y -rm[$nearest] -a y -endl -wait -1

    # Insert new active point.
    -elif {@{!,b}&1" && "@{!,x}>=0}
      xy=({@{!,x}*@{0,w}/@{!,w}},{@{!,y}*@{0,h}/@{!,h}})              # Point coordinates in the image basis.
      --shift[1] 0,-1,0,0,2 -+[-1] [1] -/[-1] 2                       # Compute center of segments.
      $xy --[-2,-1] -sqr[-1] -s[-1] x -+[-2,-1]                       # Compute distance vector to segments.
      (@{-1,c}) ns=@{-1,1} -rm[-2,-1]                                 # Get nearest segment.
      -l[1] -s y -i[{$ns+1}] $xy -a y -endl                           # Insert new point at right position.
      active={$ns+1}                                                  # Set new active point as newly inserted.
    -endif

  -while {@!" && "!@{!,ESC}" && "!@{!,Q}}

  # Render spline as a tertiary mask for output.
  --shift[1] 0,-1,0,0,2 --shift[1] 0,1,0,0,2 --[-2,-1] -*[-1] $roundness
  [0],[0],1,1,2 -rm[0]
  -repeat @{1,h} -spline[-1] @{0,0-1},@{1,0-1},@{0,2-3},@{1,2-3},1,1 -shift[0] 0,-1,0,0,2 -shift[1] 0,-1,0,0,2 -done
  -flood[-1] 0,0,0,0,0,1,0

  # Exit properly.
  -rm[0,1] -w 0 -v +

#@gmic x_tictactoe
#@gmic : Launch tic-tac-toe game.
x_tictactoe :
  -e[] "\n
------ Tic-Tac-Toe game -----------------\n
----\n
---- Use mouse to select positions of the\n
---- symbols. Close window to exit game.\n
----\n
-----------------------------------------"
  -v -                            # Become quiet.

  # Allocate variables.
  message=0                       # [-7] : State message.
  counter=0                       # [-6] : Turn counter (0 to 8).
  player=0                        # [-5] : Current player (0 or 1).
  state=0                         # [-4] : Board state.
  tmp3=0                          # [-3] : Temporary variable 3.
  tmp2=0                          # [-2] : Temporary variable 2.
  tmp1=0                          # [-1] : Temporary variable 1.
  -_x_tictactoe2                  # Generate board.
  -w[-1] -1,-1,0,0," "            # Init display window.

  # Start main loop.
  -do

    # Set state message depending on the current player.
    -if $player message="Tic-Tac-Toe (O to play)"
    -else message="Tic-Tac-Toe (X to play)"
    -endif

    # Select position by the user.
    -do                                                                       # Enter event loop.
      -w[] {w},{h},0,0,"[G'MIC] "$message -wait                               # Wait for events and force window size if necessary.
      -if {!@!} -w[] 0 -rm -v + -return -endif                                # Quit properly if window has been closed.
      -if {@{!,b}&1" && "@{!,x}>20" && "@{!,y}>20" && "@{!,x}<400" && "@{!,y}<400} # If mouse button has been pressed on the board area.
        tmp3={int((@{!,x}-15)/130)}                                                # Get x-coord of the selected position (0,1 or 2).
        tmp2={int((@{!,y}-15)/130)}                                                # Get y-coord of the selected position (0,1 or 2).
        tmp1={4^($tmp2*3+$tmp3)}                                                   # Get state code of the selected position.
        -if {int($state/$tmp1)%4} tmp1=-1 -endif                                   # Check availability of the selected position.
      -else tmp1=-1 -endif                                                    # If no mouse button, do nothing but loop.
    -while {$tmp1<0}                                                          # Go on until a valid position has been selected.

    # Draw symbol on selected position and update board state.
    -_x_tictactoe{$player%2}                                                  # Generate the symbol sprite and his mask.
    -j[-3] [-2],{"130*"$tmp3" + 15+?(-5,5)"},\                                # Draw symbol at its position (with some fuzzyness).
                {"130*"$tmp2" + 15+?(-5,5)"},0,0,1,[-1]
    -rm[-2--1]                                                                # Delete the sprite and the mask (not needed anymore).
    -w[-1]                                                                    # Update display window.
    state={$state+(1+$player)*$tmp1}                                          # Update the board state.

    # Check for a winning configuration.
    (21,1344,86016,4161,16644,66576,65793,4368;\                              # The list of winning configurations.
     0,0,0,0,1,2,0,0;\                                                        # Corresponding X coords for the stroke.
     0,1,2,0,0,0,0,0;\                                                        # Corresponding Y coords for the stroke.
     3,3,3,4,4,4,5,6)                                                         # Corresponding indice of the stroke sprite.
    -repeat {w}                                                               # Start to check configurations.
      tmp1=@{-1,$>}                                                           # Save the current configuration code (used several times).
      -if {($state&$tmp1)==$tmp1||($state&(2*$tmp1))==2*$tmp1}                # If a winner has been found.
        -_x_tictactoe@{-1,($>,3)}                                               # Generate the stroke symbol and his mask.
        -j[-4] [-2],{130*@{-3,($>,1)}+?(-5,5)},\                            # And display it on the board at its position.
                        {130*@{-3,($>,2)}+?(-5,5)},0,0,1,[-1] -rm[-2--1]
        -if {($state&$tmp1)==$tmp1} -w[-2] -1,-1,0,0,"Tic-Tac-Toe (X won !)"
        -else -w[-2] -1,-1,0,0,"Tic-Tac-Toe (O won !)"                          # Update display window.
        -endif
        -do -wait -w[] @{!,w},@{!,h} -while @!                                  # Wait for the window to be closed.
        -rm -w[] 0 -v + -return                                                 # And return properly.
      -endif
    -done                                                                     # Go on until all configurations have been checked.
    -rm[-1]                                                                   # Delete winning configuration data.

    player={($player+1)%2}                                                  # Select next player.
    counter={$counter+1}                                                    # Increment turn counter.
  -while {$counter<9}                                                       # Loop to next move until all positions have been filled.

  # Here, the game has been ended without winners.
  -w[] -1,-1,0,0,"Tic-Tac-Toe (Tied game !)"                                # Change window title.
  -do -wait -w[] @{!,w},@{!,h} -while @!                                    # Wait for the window to be closed.
  -w[] 0 -rm -v +                                                           # Return properly.

# Generate Tic-Tac-Toe graphics.
_x_tictactoe : # Apply a hand-drawing effect.
  -spread[-1] 4 -b[-1] 6 -sharpen[-1] 0.8 -n[-1] 0,1

__x_tictactoe : # Apply color to last image and generate corresponding opacity mask.
  --f[-1] 1-i --n[-2] $2,255 --n[-3] $3,255 -n[-4] $1,255 -a[-4,-2,-1] c

_x_tictactoe0 : # Generate a 'X' and his mask.
  128,128,1,1,1 -line[-1] 15%,15%,85%,85%,1,0 -line[-1] 15%,85%,85%,15%,1,0 -erode[-1] 12 -_x_tictactoe -deform[-1] 4 -__x_tictactoe 40,40,160

_x_tictactoe1 : # Generate a 'O' and his mask.
  128,128,1,1,1 -ellipse[-1] 50%,50%,22%,22%,0,1,0 -ellipse[-1] 50%,50%,15%,15%,0,1,1 -_x_tictactoe -deform[-1] 4 -__x_tictactoe 160,40,160

_x_tictactoe2 : # Generate the board.
  391,391,1,1,"!(x%130) || !(y%130)" -r[-1] 421,421,1,1,0,0,0.5,0.5 -dilate[-1] 3 -_x_tictactoe -f[-1] 1-i
  100%,100% -noise[-1] 10 -b[-1] 8,0 -sharpen[-1] 1.5 -n[-1] 220,255 -*[-2,-1] -to_rgb[-1]

_x_tictactoe3 : # Generate an horizontal stroke and his mask.
  421,130,1,1,1 -line[-1] 10%,60%,90%,60%,1,0 -erode[-1] 6 -_x_tictactoe -rotate[-1] {?(-6,6)},1,1,50%,50% -__x_tictactoe 180,10,10

_x_tictactoe4 : # Generate a vertical stroke and his mask.
  -_x_tictactoe3 -transpose[-2--1]

_x_tictactoe5 : # Generate a ++ diagonal stroke and his mask.
  421,421,1,1,1 -line[-1] 10%,10%,90%,90%,1,0 -erode[-1] 6 -_x_tictactoe -__x_tictactoe 180,10,10

_x_tictactoe6 : # Generate a +- diagonal stroke and his mask.
  421,421,1,1,1 -line[-1] 10%,90%,90%,10%,1,0 -erode[-1] 6 -_x_tictactoe -__x_tictactoe 180,10,10

#@gmic x_whirl : _opacity>=0
#@gmic : Launch fractal whirl demo.
#@gmic : Default values : 'opacity=0.2'.
x_whirl : -check ${1=0.2}>=0
  -e[] "\n
------ Fractal whirl demo ------------------------\n
----\n
---- Keys 'ESC' or 'Q' to exit.\n
----\n
--------------------------------------------------"

  -v -
  5,5,1,3 256,256,1,3 [-1] -w[-1] 512,512,0,0,"[G'MIC] Fractal whirl demo"
  tangle=0 tzoom=0 xc={(w-@{-3,w})/2} yc={(h-@{-3,h})/2}
  -do
    -rand[-3] 0,255 -j[-2] [-3],$xc,$yc,0,0
    -rotate[-2] {8*sin($tangle)},0,0,{w/2+?(-2,2)},{h/2},{1.03+0.02*sin($tzoom)}
    tangle={$tangle+0.001} tzoom={$tzoom+0.02}
    -j[-1] [-2],0,0,0,0,$1 -w[-1] -wait 20
  -while {@!" && "!@{!,ESC}" && "!@{!,Q}}
  -rm[-3,-2] -w[] 0 -v +

#------------------------------------
#
#@gmic :: PINK-library operators
#
#------------------------------------

_wrbytepnk :
  -output_pink3d ${1}.pnk

_xpink :
  filename=@{-file_rand}
  -if {!@{-is_windows}}
    -x "which $1 >/dev/null 2>&1"
    -if {@{}!=0} -error "executable "$1" not found in PATH, status = "@{}"!! Returning!!\n" -return -endif
    -output_pink3d ${filename}.pnk -x "$1 "${filename}".pnk $2 "${filename}"_o.pnk >/dev/null 2>&1"
  -else
    -output_pink3d ${filename}.pnk -x "$1 "${filename}".pnk $2 "${filename}"_o.pnk"
  -endif
  status=@{}
  -file_rm ${filename}.pnk
  -if {$status!=0\ &&\ {$1'!='seuilauto} -error "exec Status is "${status}"." -return
  -elif ${filename}_o.pnk -i ${filename}_o.pnk -file_rm ${filename}_o.pnk -k[-1]
  -else -error "exec Error !!" -endif

_xpinks :
  s=@{-1,s} -if {$s>1} -s[-1] c -endif
  -repeat @# -l[@{>,-1}]  -_xpink $1,"$2" -k[-1] -endl -done
  -if {$s>1} -a[-$s--1] c -endif

_xframe :
  -line 0%,0%,100%,0% -line 0%,100%,100%,100% -line 0%,0%,0%,100% -line 100%,0%,100%,100%

#@gmic output_pink3d : filename
#@gmic : Save selected images as P5-coded PPM files (PINK extension for 3d volumetric images).
output_pink3d :
  -e[^-1] "Output image$? as file '$1' (in 3d pink extension of P5-coded PPM format)."
  -v - -if {@#==1} filename0="$1"
  -else -repeat @# filename$>=@{-filename\ "\"$1\"",$>} -done
  -endif
  -repeat @# -l[$>]
    -if {d==1} -o[-1] ppm:${filename$>}  # 2d image, save as regular PPM format.
    -else                                # 3d image, save as PINK PPM extension.
      ({'P5\n{w}\ {h}\ {d}\n255\n'})
      --channels[-2] 0 -y[-1] x -a[-2,-1] x
      -o[-1] raw:${filename$>},uchar
      -rm[-1]
    -endif
  -endl -done -v +

#@gmic pink
#@gmic : Pink wrapper name,p1, .. ,pn (requires the PINK library to be installed).
#@gmic : (http://pinkhq.com/)
#@gmic : prepares input, calls external "name input p1 ... pn output" and reads output (/tmp)
#@gmic : $ image.jpg --pink asfr,5 -pink[0] asf,5
#@gmic : $ image.jpg --blur 2 -pink maxima,4
pink : -v -
  -if {$#>1} ({"'${2--1}'"}) -replace[-1] {','},{"' '"} p=@{-1,t} -rm[-1] -else p=" " -endif
  -v + -e[^-1] "Call pink package with cmd: \"$1$? "$p"$?\"." -v -
  -repeat @# -l[@{>,-1}] -_xpinks $1,$p -endl -done -v +

#@gmic pink_grayskel : _connectivity={ 4 | 8 | 6 | 26 }, _lambda=0
#@gmic : (http://pinkhq.com/grayskel_8c.html)
#@gmic : Grayscale homotopic skeleton (requires the PINK library to be installed).
#@gmic : Default values : 'connectivity=4' and 'lambda=0'.
#@gmic : $ image.jpg --pink_grayskel , --pink_grayskel[0] ,10 --pink_grayskel[0] ,100 -append_tiles 2
pink_grayskel : -skip ${1=4},${2=0}
  -check "${1=4}==4 || $1==8 || $1==6 || $1==26"
  -repeat @# -l[@{>,-1}] -_xpinks "grayskel","null $1 $2" -endl -done

#@gmic pink_heightmaxima : _connectivity={ 4 | 8 | 6 | 26 },_height=1
#@gmic : (http://pinkhq.com/heightmaxima_8c.html)
#@gmic : Heightmaxima filtering (requires the PINK library to be installed).
#@gmic : Default values : 'connectivity=4' and 'height=1'.
#@gmic : $ image.jpg --blur 2 --pink_heightminima ,15 --pink_heightmaxima[0,1] ,15 --[-3,-1] --[-3,-1] -k[-1,-2]
pink_heightmaxima : -check "${1=4}==4 || $1==8 || $1==6 || $1==26" -skip ${2=1}
  -e[^-1] "Filter by heightmaxima exec with connectivity $1 height $2."
  -v - -repeat @# -l[@{>,-1}]
    s=@{-1,s} -if {$s>1} -s[-1] c -endif
    -repeat @# -l[@{>,-1}] -_xpink "heightmaxima","$1 $2" -k[-1] -endl -done
    -if {$s>1} -a[-$s--1] c -endif
  -endl -done -v +

#@gmic pink_heightminima : _connectivity={ 4 | 8 | 6 | 26 },_height=1
#@gmic : (http://pinkhq.com/heightminima_8c.html)
#@gmic : Heightminima filtering (requires the PINK library to be installed).
#@gmic : Default values : 'connectivity=4' and 'height=1'.
#@gmic : $ image.jpg --blur 2 --pink_heightminima ,15 --pink_heightmaxima[0,1] ,15 --[-3,-1] --[-3,-1] -k[-1,-2]
pink_heightminima : -check "${1=4}==4 || $1==8 || $1==6 || $1==26" -skip ${2=1}
  -e[^-1] "Apply filter by heightminima exec with connectivity $1 height $2."
  -v - -repeat @# -l[@{>,-1}]
    s=@{-1,s} -if {$s>1} -s[-1] c -endif
    -repeat @# -l[@{>,-1}] -_xpink "heightminima","$1 $2" -k[-1] -endl -done
    -if {$s>1} -a[-$s--1] c -endif
  -endl -done -v +

#@gmic pink_htkern : _connectivity={ 4 | 8 | 6 | 26 }, _type={""|u}
#@gmic : (http://pinkhq.com/htkern_8c.html)
#@gmic : (http://pinkhq.com/htkernu_8c.html)
#@gmic : Grayscale ultimate homotopic thinning/thickening without condition (requires the PINK library to be installed).
#@gmic : Default values : 'connectivity=4' and 'type=""'.
#@gmic : $ image.jpg --pink_htkern ,u --pink_htkern[0] , ---[-1,-2] -rm[0]
pink_htkern : -skip ${1=4},${2=""}
  -repeat @# -l[@{>,-1}] -_xpinks htkern$2,"null $1" -endl -done

#@gmic pink_lvkern : _connectivity={ 4 | 8 | 6 | 26 }, _type={""|u}
#@gmic : (http://pinkhq.com/lvkern_8c.html)
#@gmic : (http://pinkhq.com/lvkernu_8c.html)
#@gmic : Grayscale ultimate leveling thinning/thickening without condition (requires the PINK library to be installed).
#@gmic : Default values : 'connectivity=4' and 'type=""'.
#@gmic : $ image.jpg -pink_lvkern ,u
pink_lvkern : -skip ${1=4},${2=""}
  -check "${1=4}==4 || $1==8 || $1==6 || $1==26"
  -repeat @# -l[@{>,-1}] -_xpinks lvkern${2},"null $1" -endl -done

#@gmic pink_reg_minima : _connectivity={ 4 | 8 | 6 | 26 }
#@gmic : (http://pinkhq.com/minima_8c.html)
#@gmic : Regional minima (requires the PINK library to be installed).
#@gmic : Default values : 'connectivity=4'.
#@gmic : $ image.jpg --blur 2 -pink_reg_minima ,
pink_reg_minima : -check "${1=4}==4 || $1==8 || $1==6 || $1==26"
  -e[^-1] "Compute regional minima exec with connectivity $1."
  -v - -repeat @# -l[@{>,-1}]
    s=@{-1,s} -if {$s>1} -s[-1] c -endif
    -repeat @# -l[@{>,-1}]  -_xpink "minima","$1" -k[-1] -endl -done
    -if {$s>1} -a[-$s--1] c -endif
  -endl -done -v +

#@gmic pink_skelcurv : _prio={0|1|2|3|4|8|6|26},_connectivity={ 4 | 8 | 6 | 26 },_inhibit={""}
#@gmic : (http://pinkhq.com/skelcurv_8c.html)
#@gmic : Curvilinear binary skeleton guided by a priority function or image (requires the PINK library to be installed).
#@gmic : Default values : 'prio=0', 'connectivity=4' and 'inhibit=""'.
#@gmic : $ image.jpg -t 50% {w},{h} -f[-1] 'if(x>w/2,255,0)' tp=@{-path_tmp} -o[-1] ${tp}/inhibit.pgm -rm[-1] --pink_skelcurv[0] , --pink_skelcurv[0] ,,${tp}/inhibit.pgm -x "rm "${tp}"/inhibit.pgm"
#@gmic : $ image.jpg -t 50% --pink_skelcurv , --pink_skelcurv[-2] ,8
pink_skelcurv : -skip ${1=0},${2=4},${3=""}
  -e[^-1] "Curvilinear binary skeleton guided by a priority function or image from image$?, prio=$1, connectivity=$2, inhibit=$3."
  -repeat @# -l[@{>,-1}] -_xpinks "skelcurv","$1 $2 $3" -endl -done

#@gmic pink_skelend : _connectivity={ 4 | 8 | 6 | 26 },_n=0
#@gmic : (http://pinkhq.com/skelend_8c.html)
#@gmic : Homotopic skeleton of a 2d or 3d binary image with dynamic detection of end points (requires the PINK library to be installed).
#@gmic : Default values : 'connectivity=4' and 'n=0'.
#@gmic : $ image.jpg -t 50% --pink_skelend , --pink_skelend[-2] ,-1
pink_skelend : -skip ${1=4},${2=0}
  -repeat @# -l[@{>,-1}] -_xpinks "skelend","$1 $2" -endl -done

#@gmic pink_skeleton : _prio={0|1|2|3|4|8|6|26},_connectivity={ 4 | 8 | 6 | 26 },_inhibit={""}
#@gmic : (http://pinkhq.com/skeleton_8c.html)
#@gmic : Ultimate binary skeleton guided by a priority image (requires the PINK library to be installed).
#@gmic : Default values : 'prio=0', 'connectivity=4' and 'inhibit=""'.
#@gmic : $ image.jpg -t 50% --pink_skeleton[-1] ,
 pink_skeleton : -skip ${1=0},${2=4},${3=""}
  -repeat @# -l[@{>,-1}] -_xpinks "skeleton","$1 $2 $3" -endl -done

#@gmic pink_skelpar : _algorithm={0..29},_nsteps=_1,_inhibit=""
#@gmic : (http://pinkhq.com/skelpar_8c.html)
#@gmic : Parallel binary skeleton (requires the PINK library to be installed).
#@gmic : Default values : 'algorithm=4', 'nsteps=-1' and 'inhibit=""'.
#@gmic : $ image.jpg -t 50% --pink_skelpar[-1] 0 --pink_skelpar[-1] 2
pink_skelpar : -skip ${1=4},${2=-1},${3=""}
  -repeat @# -l[@{>,-1}] -_xframe -_xpinks "skelpar","$1 $2 $3" -endl -done

#@gmic pink_wshed : _connectivity={ 4 | 8 | 6 | 26 },_inverse={ 0 | 1 },_height=0
#@gmic : (http://pinkhq.com/wshedtopo_8c.html)
#@gmic : Watershed (requires the PINK library to be installed).
#@gmic : Default values : 'connectivity=4', 'inverse=0' and 'height=0'.
#@gmic : $ image.jpg --pink_wshed ,1,5 -pink_wshed[0] ,,5
pink_wshed : -check "${1=4}==4 || $1==8 || $1==6 || $1==26" -skip ${2=0},${3=0}
  -e[^-1] "Compute wshedtopo exec with connectivity $1 inversion $2 height $3."
  -v - -repeat @# -l[@{>,-1}]
    s=@{-1,s} -if {$s>1} -s[-1] c -endif
    -if {@{-1,d}==1}
      -check "${1=4}==4 || $1==8"
      -repeat @# -l[@{>,-1}]
        -if {$2!=0} -negative -endif
        -fill max(min(i,255),0)
        -if {$3>=0} -pink heightminima,$1,$3 -endif
        -pink wshedtopo,$1
        -if {$2!=0} -negative -endif
      -endl -done
    -else
      -check "$1==6 || $1==26"
      -repeat @# -l[@{>,-1}]
        -if {$2!=0} -negative -endif
        -fill max(min(i,255),0)
#        -output_pink3d ${filename}.pnk
        -if {$3>=0}
          -pink heightminima,$1,$3
        -endif
        -pink wshedtopo,$1
#        -i ${filename}_.pnk
        -if {$2!=0} -negative -endif
#        -x "rm "${filename}"*" -k[-1]
      -endl -done
    -endif
    -if {$s>1} -a[-$s--1] c -endif
  -endl -done -v +

#------------------------------
#
#@gmic :: Convenience functions
#
#------------------------------

#@gmic arg : n,_arg1,...,_argN
#@gmic : Return the n-th argument of the specified argument list.
#@gmic : 'n' can be also a pattern, as '1--1' for instance.
arg :
  -m "__arg : -u ${"$1"}" -__arg ${2--1} -uncommand __arg

#@gmic at : _x,_y,_z
#@gmic : Return a specified vector-valued point (x,y,z) from the latest of the selected images.
at : -skip ${1=0},${2=0},${3=0}
  --z[-1] ${1-3},${1-3} -u @-1 -rm[-1]

#@gmic basename : file_path,_variable_name_for_folder
#@gmic : Return the basename of a file path, and opt. its folder location.
#@gmic : When specified 'variable_name_for_folder' must starts by an underscore
#@gmic : (global variable accessible from calling function).
basename : -skip ${2=unused}
  -l[] ({"'$1'"}) -replace 92,47 -s +,47
  -if {i==47} -a y $2=@{-1,t} -u ""
  -elif {@#==1} -u @{-1,t} $2=""
  -else -a[^-1] y -u @{-1,t} $2=@{-2,t}
  -endif
  -rm -endl

#@gmic bin : binary_int1,...
#@gmic : Print specified binary integers into their octal, decimal, hexadecimal and string representations.
bin :
  -v - dec=@{-bin2dec\ ${^0}} -v +
  -e[^-1] "Convert binary integer"@{"-if {$#>1} -u s -else -u \"\" -endif"}" '${^0}' to octal '"@{-dec2oct\ $dec}"',
           decimal '"$dec"', hexadecimal '"@{-dec2hex\ $dec}"' and string '"@{-dec2str\ $dec}"'."

#@gmic bin2dec : binary_int1,...
#@gmic : Convert specified binary integers into their decimal representations.
bin2dec :
  res=@{-_$0\ $1} -repeat {$#-1} res=$res,@{-_$0\ @{-arg\ {$>+2},${^0}}} -done -u $res

_bin2dec :
  ({'@{-struncase\ $1}'})
  is_negative=0
  -if {@{-1,0}==45} -z[-1] 1,100% is_negative=1 -endif
  -f[-1] "if(i>=48 && i<=49,(i-48)*2^(w-1-x),nan)"
  -u {if($is_negative,-1,1)*@{-1,+}}
  -rm[-1]

# compress_gmic
# Compress .gmic custom command files for the 'gmic' command line tool,
# by removing empty lines, and useless comments (non starting with '#@gmic').
compress_gmic :
  head_std={'"#@gmic"'}
  -s -,10
  -repeat @#
    -if {i=={'#'}}
      head=@{-1,0-{min(5,h-1)}}
      -if {$head'!='$head_std} -rm[-1] -continue
      -endif
    -else
      -l[-1] -split +,32,35 -if {@#>2} -rm[1--1] -endif -a y -endl
      -autocrop[-1] 32 -if {i==32} -rm[-1] -continue -endif
    -endif
  -mv[-1] 0 -done
  -i[1--2] (10) -a y

# compress_gmic_gimp
# Compress .gmic custom command files for the GIMP plug-in,
# by removing empty lines, and useless comments (non starting with '#@gimp').
compress_gmic_gimp :
  head_std={'"#@gimp"'}
  -s -,10
  -repeat @#
    -if {i=={'#'}}
      head=@{-1,0-{min(5,h-1)}}
      -if {$head'!='$head_std} -rm[-1] -continue
      -endif
    -else
      -l[-1] -split +,32,35 -if {@#>2} -rm[1--1] -endif -a y -endl
      -autocrop[-1] 32 -if {i==32} -rm[-1] -continue -endif
    -endif
  -mv[-1] 0 -done
  -i[1--2] (10) -a y

#@gmic dec : decimal_int1,...
#@gmic : Print specified decimal integers into their binary, octal, hexadecimal and string representations.
dec :
  -e[^-1] "Convert decimal integer"@{"-if {$#>1} -u s -else -u \"\" -endif"}" '${^0}' to binary '"@{-dec2bin\ ${^0}}"',
           octal '"@{-dec2oct\ ${^0}}"', hexadecimal '"@{-dec2hex\ ${^0}}"' and string '"@{-dec2str\ ${^0}}"'."

#@gmic dec2str : decimal_int1,...
#@gmic : Convert specifial decimal integers into its string representation.
dec2str :
  -u {`${^0}`}

#@gmic dec2bin : decimal_int1,...
#@gmic : Convert specified decimal integers into their binary representations.
dec2bin :
  res=@{-_$0\ $1} -repeat {$#-1} res=$res,@{-_$0\ @{-arg\ {$>+2},${^0}}} -done -u $res

_dec2bin : -check isint($1)
  res="" r={abs($1)}
  -do res={$r%2}$res r={int($r/2)} -while $r
  -u @{"-if {$1>=0} -u \"\" -else -u - -endif"}$res

#@gmic dec2hex : decimal_int1,...
#@gmic : Convert specified decimal integers into their hexadecimal representations.
dec2hex :
  res=@{-_$0\ $1} -repeat {$#-1} res=$res,@{-_$0\ @{-arg\ {$>+2},${^0}}} -done -u $res

_dec2hex : -check isint($1)
  res="" r={abs($1)}
  -do res=@{-_dec2hex_{$r%16}}$res r={int($r/16)} -while $r
  -u @{"-if {$1>=0} -u \"\" -else -u - -endif"}$res

_dec2hex_0 : -u 0
_dec2hex_1 : -u 1
_dec2hex_2 : -u 2
_dec2hex_3 : -u 3
_dec2hex_4 : -u 4
_dec2hex_5 : -u 5
_dec2hex_6 : -u 6
_dec2hex_7 : -u 7
_dec2hex_8 : -u 8
_dec2hex_9 : -u 9
_dec2hex_10 : -u a
_dec2hex_11 : -u b
_dec2hex_12 : -u c
_dec2hex_13 : -u d
_dec2hex_14 : -u e
_dec2hex_15 : -u f

#@gmic dec2oct : decimal_int1,...
#@gmic : Convert specified decimal integers into their octal representations.
dec2oct :
  res=@{-_$0\ $1} -repeat {$#-1} res=$res,@{-_$0\ @{-arg\ {$>+2},${^0}}} -done -u $res

_dec2oct : -check isint($1)
  res="" r={abs($1)}
  -do res={$r%8}$res r={int($r/8)} -while $r
  -u @{"-if {$1>=0} -u \"\" -else -u - -endif"}$res

#@gmic fact : value
#@gmic : Return the factorial of the specified value.
fact : -check isint($1)
  res=1 -repeat $1 res={$res*($>+1)} -done -u $res

#@gmic file_mv : filename_src,filename_dest
#@gmic : Rename or move a file from a location $1 to another location $2.
file_mv :
  -if @{-is_windows} -x "move "$1" "$2 -else -x "mv "$1" "$2 -endif

#@gmic file_rand
#@gmic : Return a random filename for storing temporary data.
file_rand :
  -do filename=@{-path_tmp}@{-file_slash}gmic{round(?(0,9))}{round(?(0,9))}{round(?(0,9))}{round(?(0,9))}{round(?(0,9))}{round(?(0,9))}
  -while $filename
  -u $filename

#@gmic file_rm : filename
#@gmic : Delete a file.
file_rm :
  -if @{-is_windows}
    1 -nm[-1] "$1" dir=@{-1,f} base=@{-1,b} ext=@{-1,x} -rm[-1] com=""
    -if {narg($dir)} com="cd \""$dir"\\\" && " -endif
    -if {narg($ext)} com=${com}"del \""$base.$ext"\"" -else com=${com}"del \""$base"\"" -endif
    -x $com
  -else
    -x "rm -f \"$1\""
  -endif

#@gmic file_slash
#@gmic : Return '/' or '\' as a path separator for filenames.
file_slash :
  -if @{-is_windows} -u "\\" -else -u "/" -endif

#@gmic filename : filename,_number1,_number2,...,_numberN
#@gmic : Return a filename numbered with specified indices.
filename : -skip "${1=default}"
  -if {$#==1} -u "$1"
  -else
  (${2--1}) -name[-1] "$1" -u @{-1,f}@{-1,b}
  -repeat {w}
    -u @{}_{int(i/100000)%10}{int(i/10000)%10}{int(i/1000)%10}{int(i/100)%10}{int(i/10)%10}{i%10}
    -shift[-1] -1
  -done
  -if {narg({'@{-1,x}'})} -u @{}.@{-1,x} -endif
  -rm[-1]
  -endif

#@gmic fitratio_wh : min_width,min_height,ratio_wh
#@gmic : Return a 2d size 'width,height' which is bigger than 'min_width,min_height' and has the specified w/h ratio.
fitratio_wh :
  -if {$3*$2>$1} -u {int($3*$2)},$2 -else -u $1,{int($1/$3)} -endif

#@gmic fitscreen : width,height,_depth
#@gmic : Return the 'ideal' size WxH for a window intended to display an image of specified size on screen.
fitscreen : -check "$1>0 && $2>0 && ${3=1}>0"
  w={if($3>1,$1+$3,$1)}
  h={if($3>1,$2+$3,$2)}
  Mw={int(0.85*@{!,u})}
  Mh={int(0.85*@{!,v})}
  -if {$w<128} h={int($h*128/$w)} w=128 -endif
  -if {$h<128} w={int($w*128/$h)} h=128 -endif
  -if {$w>$Mw} h={max(1,int($h*$Mw/$w))} w=$Mw -endif
  -if {$h>$Mh} w={max(1,int($w*$Mh/$h))} h=$Mw -endif
  w={max($w,128)}
  h={max($h,128)}
  -u $w,$h

#@gmic gcd : a,b
#@gmic : Return the GCD (greatest common divisor) between a and b.
gcd : -check "isint($1) && isint($2) && $1*$2!=0"
  -_gcd {max(abs($1),abs($2))},{min(abs($1),abs($2))}

_gcd :
  r={$1%$2} -if $r -u @{"-_gcd "$2,$r} -else -u $2 -endif

# Function useful to display help of commands, in interactive shell mode (linux only)
# (already documented as a built-in command).
help : -skip ${1=""}
  -v -
  -if {narg($1)}
    -x "gmic -h $1 | tail -n +6 | head -n -1"
  -else
    -x "gmic -h | head -n 5"
  -endif
  -v +
h :
  -help $*

#@gmic hex : hexadecimal_int1,...
#@gmic : Print specified hexadecimal integers into their binary, octal, decimal and string representations.
hex :
  -v - dec=@{-hex2dec\ ${^0}} -v +
  -e[^-1] "Convert hexadecimal integer"@{"-if {$#>1} -u s -else -u \"\" -endif"}" '${^0}' to binary '"@{-dec2bin\ $dec}"',
           octal '"@{-dec2oct\ $dec}"', decimal '"$dec"' and string '"@{-dec2str\ $dec}"'."

#@gmic hex2dec : hexadecimal_int1,...
#@gmic : Convert specified hexadecimal integers into their decimal representations.
hex2dec :
  res=@{-_$0\ $1} -repeat {$#-1} res=$res,@{-_$0\ @{-arg\ {$>+2},${^0}}} -done -u $res

_hex2dec :
  ({'@{-struncase\ $1}'})
  is_negative=0
  -if {@{-1,0}==45} -z[-1] 1,100% is_negative=1 -endif
  -f[-1] "if(i>=48 && i<=57,i-48,if(i>=97 && i<=102,i-87,nan))*16^(w-1-x)"
  -u {if($is_negative,-1,1)*@{-1,+}}
  -rm[-1]

#@gmic hex2str : hexadecimal_string
#@gmic : Convert specified hexadecimal string into a string.
hex2str : -skip ${1=""}
  -if {!narg("$1")} -return -endif
  ({'$*'})
  -if {w<2} -rm[-1] -u "" -return -endif
  -r[-1] 2,{w/2},1,1,-1 -f[-1] 'if(i>=97,i-87,i-48)' -f[-1] 'if(x==0,i*16+i(x+1),0)' -columns[-1] 0
  -u @{-1,t} -rm[-1]

#@gmic img82hex
#@gmic : Convert selected 8bits-valued vectors into their hexadecimal representations (ascii-encoded).
img82hex :
  -e[^-1] "Convert 8bits-valued vector$? into hexadecimal representations (ascii-encoded)."
  -v - -mod 256 -y y
  -repeat @#
    --f[$>] 'v=int(i)&15;v+if(v<10,48,87)'  # lower digit.
    -f[$>] 'v=int(i)>>4;v+if(v<10,48,87)'   # higher digit.
    -a[$>,-1] x
  -done -v +

#@gmic hex2img8
#@gmic : Convert selected hexadecimal representations (ascii-encoded) into 8bits-valued vectors.
hex2img8 :
  -e[^-1] "Convert hexadecimal representation$? (ascii-encoded) into 8bits-valued vectors."
  -v - -repeat @#
    -s[-1] x,2 -f[-2,-1] 'if(i>=97,i-87,i-48)' -*[-2] 16 -+[-2,-1]
  -mv[-1] 0 -done -v +

#@gmic is_3d
#@gmic : Return 1 if one of the selected image is a 3d object, 0 otherwise.
is_3d :
  res=0
  -repeat @# --lines[$>] 0,5 -round[-1] 1,-1 res={$res|{@-1'=='67,73,109,103,51,100}} -rm[-1] -done
  -u $res

#@gmic is_percent : string
#@gmic : Return 1 if specified string ends with a '%', 0 otherwise.
is_percent :
  ({'"$1"'}) -u {@{-1,{w-1}}==37} -rm[-1]

#@gmic is_windows
#@gmic : Return 1 if current computer OS is Windows, 0 otherwise.
is_windows :
  -if {narg($OS)==1" && "narg($WINDIR)==1} -u 1 -else -u 0 -endif

#@gmic max_s
#@gmic : Return the maximal s size of selected images.
max_s :
  -_max_s @{"-_max_whds 4"}

_max_s :
  -u $4

#@gmic max_wh
#@gmic : Return the maximal wxh size of selected images.
max_wh :
  -_max_whds 2

#@gmic max_whd
#@gmic : Return the maximal wxhxd size of selected images.
max_whd :
  -_max_whds 3

#@gmic max_whds
#@gmic : Return the maximal wxhxdxs size of selected images.
max_whds :
  -_max_whds 4

_max_whds :
  w=0 h=0 d=0 s=0
  -repeat @#
    w={max($w,w)}
    h={max($h,h)}
    d={max($d,d)}
    s={max($s,s)}
  -mv[-1] 0 -done
  -if {$1>=4} -u $w,$h,$d,$s
  -elif {$1==3} -u $w,$h,$d
  -elif {$1==2} -u $w,$h
  -else -u $w
  -endif

#@gmic min_s
#@gmic : Return the minimal s size of selected images.
min_s :
  -_min_s @{"-_min_whds 4"}

_min_s :
  -u $4

#@gmic min_wh
#@gmic : Return the minimal wxh size of selected images.
min_wh :
  -_min_whds 2

#@gmic min_whd
#@gmic : Return the minimal wxhxd size of selected images.
min_whd :
  -_min_whds 3

#@gmic min_whds
#@gmic : Return the minimal wxhxdxs size of selected images.
min_whds :
  -_min_whds 4

_min_whds :
  w=0 h=0 d=0 s=0
  -repeat @#
    w={min($w,w)}
    h={min($h,h)}
    d={min($d,d)}
    s={min($s,s)}
  -mv[-1] 0 -done
  -if {$1>=4} -u $w,$h,$d,$s
  -elif {$1==3} -u $w,$h,$d
  -elif {$1==2} -u $w,$h
  -else -u $w
  -endif

#@gmic oct : octal_int1,...
#@gmic : Print specified octal integers into their binary, decimal, hexadecimal and string representations.
oct :
  -v - dec=@{-oct2dec\ ${^0}} -v +
  -e[^-1] "Convert octal integer"@{"-if {$#>1} -u s -else -u \"\" -endif"}" '${^0}' to binary '"@{-dec2bin\ $dec}"', decimal '"$dec"',
           hexadecimal '"@{-dec2hex\ $dec}"' and string '"@{-dec2str\ $dec}"'."

#@gmic oct2dec : octal_int1,...
#@gmic : Convert specified octal integers into their decimal representations.
oct2dec :
  res=@{-_$0\ $1} -repeat {$#-1} res=$res,@{-_$0\ @{-arg\ {$>+2},${^0}}} -done -u $res

_oct2dec :
  ({'@{-struncase\ $1}'})
  is_negative=0
  -if {@{-1,0}==45} -z[-1] 1,100% is_negative=1 -endif
  -f[-1] "if(i>=48 && i<=55,(i-48)*8^(w-1-x),nan)"
  -u {if($is_negative,-1,1)*@{-1,+}}
  -rm[-1]

#@gmic padint : number,_size>0
#@gmic : Return a integer with 'size' digits (eventually left-padded with '0').
padint : -skip ${2=4}
  -u "" -repeat $2 -u @{}{int($1/10^$<)%10} -done

#@gmic path_tmp
#@gmic : Return a path to store temporary files (whose value is OS-dependent).
path_tmp :
  -u ""
  -if {narg({'${TMP}'})} -u ${TMP}
  -elif {narg({'${TEMP}'})} -u ${TEMP}
  -elif {narg({'${TMPDIR}'})} -u ${TMPDIR}
  -elif {narg({'${HOME}'})} -u "/tmp"
  -else -u ""
  -endif

#@gmic path_user
#@gmic : Return a path to store persistent configuration files for one user (whose value is OS-dependent).
path_user :
  -u ""
  -if {narg({'${APPDATA}'})} -u ${APPDATA}
  -elif {narg({'${HOME}'})} -u ${HOME}
  -else -u ""
  -endif

#@gmic quote : string
#@gmic : Return a "quotified" version of the string.
quote :
  -u "$*"

#@gmic reset
#@gmic : Reset global parameters of the interpreter environment.
reset :
  -e[^-1] "Reset global parameters of the interpreter environment."
  -v - -db3d 1 -b3d -m3d 4 -md3d -1 -f3d 800 -l3d -sl3d 0.15 -ss3d 0.8 -v +

#@gmic RGB
#@gmic : Return a random int-valued RGB color.
RGB :
  -u {round(?(255))},{round(?(255))},{round(?(255))}

#@gmic RGBA
#@gmic : Return a random int-valued RGBA color.
RGBA :
  -u {round(?(255))},{round(?(255))},{round(?(255))},{round(?(255))}

#@gmic str : string
#@gmic : Print specified string into its binary, octal, decimal and hexadecimal representations.
str : -skip $1
  -v - dec={'$*'} -v +
  -e[^-1] "Convert string '$*' to binary '"@{-dec2bin\ $dec}"', octal '"@{-dec2oct\ $dec}"', decimal '"$dec"' and
           hexadecimal '"@{-dec2hex\ $dec}"'."

#@gmic str2hex : string
#@gmic : Convert specified string into a sequence of hexadecimal values.
str2hex :
  ({'"$*"'}) -lines[-1] 0,1 -f[-1] 'if(y==0,int(i/16),i(x,y-1)%16)' -f[-1] 'if(i<=9,48+i,87+i)' -transpose[-1] -u @{-1,t} -rm[-1]

#@gmic stresc : val1,...,valN
#@gmic : Return escaped string from specified ascii codes.
stresc :
  ($*) -c[-1] 32,255 -y[-1] y [-1]
  -f[-2] 'if(i==32||i==34||i==36||i==44||i==64||i==92||i==123||i==125,92,-1)' -a[-2,-1] x
  -discard[-1] -1 -u @{-1,t} -rm[-1]

#@gmic strcat : string1,string2,...
#@gmic : Return the concatenation of all strings passed as arguments.
strcat :
  $=s res="$1" -repeat {$#-1} res=$res${s{$>+2}} -done
  -u $res

#@gmic strcmp : string1,string2
#@gmic : Return 1 if the two strings are equal, 0 otherwise.
strcmp :
  (0,{'"$1"'}) ({w},{'"$2"'}) -=[-2] {w} --[-2,-1] -abs[-1] -u {!@{-1,+}} -rm[-1]

#@gmic strlen : string1
#@gmic : Return the length of specified string argument.
strlen :
  ({'"$1"'}) -u {w} -rm[-1]

#@gmic strreplace : string,search,replace
#@gmic : Search and replace substrings in an input string.
strreplace :
  ls=@{"-strlen \"$2\""}
  lr={@{"-strlen \"$3\""}-1}
  -l[] ({'"$1"'}) -s +,{'"$2"'} -s y,-$ls
  -repeat @# -if {@{$>,t}'=='"$2"} -lines[$>] 0,$lr -f[$>] {'"$3"'} -endif -done
  -a y -u @{-1,t} -rm -endl

#@gmic struncase : string
#@gmic : Return a lower-case version of the specified string.
struncase :
  ({'"$*"'}) -+[-1] 'if(i>=65&&i<=90,32,0)' -u @{-1,t} -rm[-1]

#@gmic tic
#@gmic : Initialize tic-toc timer.
#@gmic : Use it in conjunction with '-toc'.
tic :
  -e "Initialize timer."
  -v - __tic=@| -v +

#@gmic toc
#@gmic : Display elapsed time of the tic-toc timer since the last call to '-tic'.
#@gmic : Use it in conjunction with '-tic'.
toc :
  -e "Elapsed time : "{@|-$__tic}" s".

#-----------------------------
#
#@gmic :: Others
#
#-----------------------------

#@gmic gpt : _scorefile,_number_of_sessions>=0
#@gmic : Generate score board for the GPT championship (GREYC Poker Tour).
#@gmic : $ -gpt ,
gpt : -skip "${1=http://www.greyc.ensicaen.fr/~dtschump/gpt.raw}" -skip ${2=0},${3=0}
  -e[^-1] "Generate score board for GPT-like championship (GREYC Poker Tour), from file '$1'."
  -v -

  # Load score file and generate score field.
  #------------------------------------------
  -rm -i raw:$1,uchar -s[-1] -,10 -transpose                           # Split score file into lines.
  -repeat @# -if {i=={'#'}} -rm[-1] -else -mv[-1] 0 -endif -done       # Remove comment lines.
  -repeat @# -l[$>]
    -s -,{'\ '}
    -if @#
      -if {@#!=4} -error[0--4] "Invalid score file (line "{$>+1}" defines "@#" items instead of 4)." -endif
      player$>_name=@{0,t}
      player$>_url=@{1,t}
      player$>_file=@{2,t}
      (@{3,t}) -rm[0-3]
    -endif
  -endl -done
  -+ 1 -a y,1 -- 1
  -if {$2>0} -z[-1] {max(0,w-$2)},100%          # Keep only last Nth sessions.
  -elif {$2<0} -z[-1] {w-1-((w-1)%-$2)},100%    # Keep only sessions of the last Nth-session tournament.
  -endif

  # Remove non-players in 'alternate' score boards.
  #------------------------------------------------
  -if $2 -s y -repeat @# -if {@{$<,M}<0}
    i=$< -repeat {@#-$i}
      player{$i+$>}_name=${player{$i+$>+1}_name}
      player{$i+$>}_url=${player{$i+$>+1}_url}
      player{$i+$>}_file=${player{$i+$>+1}_file}
    -done
    -rm[$<] -endif -done -a y
  -endif
  -nm[-1] scores

  # Set global variables.
  #-----------------------
  row_height={if($2,24,48)}

  # Compute session winners and losers
  # (must be done before rounding scores to integers!).
  #----------------------------------------------------
  --l[scores] -s y -max -endl --==[scores,-1] -rm[-2]
  -nm[-1] winners
  --l[scores] -replace[-1] -1,1e8 -s y -min -endl --==[scores,-1] -rm[-2]
  -nm[-1] losers
  --l[winners] -s y -+ -endl
  -nm[-1] nb_winners
  --l[losers] -s y -+ -endl
  -nm[-1] nb_losers

  # Compute players ranks for each session.
  # (must be done before rounding scores to integers!).
  #----------------------------------------
  --l[scores] -s x -r 2,100%,1,1,0 -f 'if(x,y,i)' -sort -,y
  -r 3,100%,1,1,0,0,1,0 -f 'if(x,i,y+1)'
  -repeat {h} -f 'if(!x,if(i(1,y)==i(1,y-1),i(0,y-1),i),i)' -done            # Manage ax-aequo ranks.
  -mirror x -sort +,y -z 1,2 -f 'if(i(0,y)==-1,-1,i)'
  -z 1,1 -a x -endl
  -nm[-1] ranks

  # Round scores to nearest integer.
  #---------------------------------
  -round[scores]

  # Compute number of players per session.
  #---------------------------------------
  --l[scores] -s x -discard -1 -f h -lines 0 -a x -endl
  -nm[-1] nb_players

  # Compute min and max scores per session.
  #----------------------------------------
  --l[scores] -s y -max -endl
  -nm[-1] max_scores
  --l[scores] -replace[-1] -1,1e8 -s y -min -endl
  -nm[-1] min_scores

  # Compute number of games per player.
  #-------------------------------------
  --l[scores] -ge 0 -s x -+ -endl
  -nm[-1] nb_games

  # Compute index of first games.
  #-------------------------------
  --l[scores] -neq -1 -s y -* 'w-x' -f xM -a y -z 0,0 -endl
  -nm[-1] first_game

  # Compute absences malus.
  #-------------------------
  --lt[scores] 0
  --l[-1] -s x -+ -endl --[-1] [first_game] # nb_absences since first played game.
  -l[-2] -f 'if(i,i,-x)' -s y -label 0 -repeat @# n={@{$>,M}} -if $n -histogram[$>] $n,1,$n -else -f[$>] 0 -endif -done
  -r 1,1,1,1,2 -a y -- 1 -max 0 -round -endl -*[-2,-1] -round[-1]
  -nm[-1] abs_malus

  # Compute player scores and corresponding ranks.
  #------------------------------------------------
  --l[scores] -f 'if(i==-1,0,i-100)' -s x -+ -endl --[-1] [abs_malus]
  --f[-1] y -a[-2,-1] x -sort[-1] -,y
  1,100%,1,1,'y+1' -a[-2,-1] x -mirror[-1] x
  -repeat {h} -f[-1] 'if(!x,if(i(2,y)==i(2,y-1),i(0,y-1),i),i)' -done        # Manage ax-aequo ranks.
  -nm[-1] rank
  --shift[-1] -1,0,0,0,2 -sort[-1] +,y -columns[-1] 1,100%
  -nm[-1] score
  sum_score=@{score,+}

  # Compute player best scores and corresponding ranks.
  #----------------------------------------------------
  --l[scores] -s x -max -- 100 -endl
  --f[-1] y -a[-2,-1] x -sort[-1] -,y
  1,100%,1,1,'y+1' -a[-2,-1] x -mirror[-1] x
  -repeat {h} -f[-1] 'if(!x,if(i(2,y)==i(2,y-1),i(0,y-1),i),i)' -done        # Manage ax-aequo ranks.
  -shift[-1] -1,0,0,0,2 -sort[-1] +,y -columns[-1] 1,100%
  -nm[-1] best_score

  # Compute previous player scores and corresponding ranks.
  #--------------------------------------------------------
  --l[scores] -columns 0,{w-2} -f 'if(i==-1,0,i-100)' -s x -+ -endl --[-1] [abs_malus]
  --f[-1] y -a[-2,-1] x -sort[-1] -,y
  1,100%,1,1,'y+1' -a[-2,-1] x -mirror[-1] x
  -repeat {h} -f[-1] 'if(!x,if(i(2,y)==i(2,y-1),i(0,y-1),i),i)' -done        # Manage ax-aequo ranks.
  -shift[-1] -1,0,0,0,2 -sort[-1] +,y -columns[-1] 1,100%
  -nm[-1] previous_score

  # Compute player chips.
  #----------------------
  --l[scores] -f 'if(i==-1,0,i-100)' -s x -+ -endl
  -nm[-1] chips
  sum_chips=@{chips,+}
  -v +
  -e "Sum of chips : "$sum_chips
  -e "Sum of scores : "$sum_score
  -v -

  # Compute player ranking trends.
  #-------------------------------
  ---[previous_score,score] -columns[-1] 1
  -nm[-1] trend

  # Compute player highest chips count.
  #------------------------------------
  --l[scores] -s y -discard -1 -unroll x -- 100 -cumul -f iM -a y -z 0,0 -endl
  --f[-1] y -a[-2,-1] x -sort[-1] -,y
  1,100%,1,1,'y+1' -a[-2,-1] x -mirror[-1] x
  -repeat {h} -f[-1] 'if(!x,if(i(2,y)==i(2,y-1),i(0,y-1),i),i)' -done        # Manage ax-aequo ranks.
  -shift[-1] -1,0,0,0,2 -sort[-1] +,y -columns[-1] 1,100%
  -nm[-1] highest_chips

  # Compute player lowest chips count.
  #------------------------------------
  --l[scores] -s y -discard -1 -unroll x -- 100 -cumul -f im -a y -z 0,0 -endl
  --f[-1] y -a[-2,-1] x -sort[-1] -,y
  1,100%,1,1,'y+1' -a[-2,-1] x -mirror[-1] x
  -repeat {h} -f[-1] 'if(!x,if(i(2,y)==i(2,y-1),i(0,y-1),i),i)' -done        # Manage ax-aequo ranks.
  -shift[-1] -1,0,0,0,2 -sort[-1] +,y -columns[-1] 1,100%
  -nm[-1] lowest_chips

  # Compute player performances and corresponding ranks.
  #-----------------------------------------------------
  ---[scores] [min_scores] [max_scores] --[-1] [min_scores] -/[-2,-1] -*[-1] 100
  -l[-1] -f 'if(i<0,-1,i)' -s y -discard -1 -f 'if(ia<0,0,ia)' -lines 0 -a y -round 1 -endl
  --f[-1] y -a[-2,-1] x -sort[-1] -,y
  1,100%,1,1,y+1 -a[-2,-1] x -mirror[-1] x
  -repeat {h} -f[-1] 'if(!x,if(i(2,y)==i(2,y-1),i(0,y-1),i),i)' -done        # Manage ax-aequo ranks.
  -shift[-1] -1,0,0,0,2 -sort[-1] +,y -columns[-1] 1,100%
  -nm[-1] performance

  # Compute player average scores and corresponding ranks.
  #--------------------------------------------------------
  --l[scores] -s y -discard -1 -- 100 -r 1,1,1,1,2 -a y -endl
  --f[-1] y -a[-2,-1] x -sort[-1] -,y
  1,100%,1,1,y+1 -a[-2,-1] x -mirror[-1] x
  -repeat {h} -f[-1] 'if(!x,if(i(2,y)==i(2,y-1),i(0,y-1),i),i)' -done        # Manage ax-aequo ranks.
  -shift[-1] -1,0,0,0,2 -sort[-1] +,y -columns[-1] 1,100%
  -nm[-1] average

  # Compute player coffee balances and corresponding ranks.
  #--------------------------------------------------------
  --!=[scores] -1                            # Coffee won.
  --*[losers,nb_players] -/[-1] [nb_losers]  # Coffee paid.
  --[-2,-1] -l[-1] -s x -+ -endl -round[-1] -*[-1] 0.4
  --f[-1] y -a[-2,-1] x -sort[-1] -,y
  1,100%,1,1,y+1 -a[-2,-1] x -mirror[-1] x
  -repeat {h} -f[-1] 'if(!x,if(i(2,y)==i(2,y-1),i(0,y-1),i),i)' -done        # Manage ax-aequo ranks.
  -shift[-1] -1,0,0,0,2 -sort[-1] +,y -columns[-1] 1,100%
  -nm[-1] coffee_balance

  # Compute arrow sprites for trends.
  #----------------------------------
  -cone3d 1.5,2 -r3d[-1] 0,1,0,90 -box3d 4,1,0 -+3d[-1] 0,-0.5 -+3d[-2,-1] -r3d[-1] 0,1,0,180
  -c3d[-1] -*3d[-1] 17 -col3d[-1] 1,1,1 -m3d 2
  128,128 -object3d[-1] [-2],50%,50%,0,1,0 -nm[-1] arrow_eq_mask
  --*[-1] 200 --*[-2] 200 --*[-3] 200 -a[-3--1] c -nm[-1] arrow_eq
  -r3d[-3] 0,0,1,35
  128,128 -object3d[-1] [-4],50%,50%,0,1,0 -nm[-1] arrow_up_mask
  --*[-1] 64 --*[-2] 255 --*[-3] 64 -a[-3--1] c -nm[-1] arrow_up
  -r3d[-5] 0,0,1,-70
  128,128 -object3d[-1] [-6],50%,50%,0,1,0 -nm[-1] arrow_down_mask
  --*[-1] 255 --*[-2] 64 --*[-3] 32 -a[-3--1] c -nm[-1] arrow_down
  -dilate[arrow_eq_mask,arrow_up_mask,arrow_down_mask] 3
  -rm[-7]

  # Render score board.
  #--------------------
  board=@#

  # Row of labels.
  i=@#
  -_gpt_field "Rank",48,$row_height,16,1,6
  -_gpt_field " ",$row_height,$row_height,16,1,6
  -_gpt_field "Name",150,$row_height,16,1,6
  -_gpt_field "Score",80,$row_height,16,1,6
  -_gpt_field "Chips\n[malus]",80,$row_height,24,1,6
  -_gpt_field "Played",48,$row_height,12,1,6
  -_gpt_field "Won/\nLost",48,$row_height,24,1,6
  -if $2 -_gpt_field "Trd",$row_height,$row_height,12,1,6
  -else -_gpt_field "Trend",$row_height,$row_height,12,1,6
  -endif
  -if $2 -_gpt_field "Stats",{2*$row_height},$row_height,12,1,6
  -else -_gpt_field "Statistics",{4*$row_height+2},$row_height,12,1,6
  -endif
  -_gpt_field "Last\n(rank)",64,$row_height,24,1,6
  -_gpt_field "Best\n(rank)",64,$row_height,24,1,6
  -_gpt_field "Highest\nchips (rank)",64,$row_height,24,1,6
  -_gpt_field "Lowest\nchips (rank)",64,$row_height,24,1,6
  -_gpt_field "Performance\n   (rank)",64,$row_height,24,1,6
  -_gpt_field "Average\n[std] (rank)",100,$row_height,24,1,6
  -_gpt_field "Coffee balance\n     (rank)",80,$row_height,24,1,6
  -a[$i--1] x

  # Retrieve maximum ranks for every field.
  max_players=@{nb_players,M}
  --z[rank] 0,0 max_rank={iM} -rm[-1]
  --z[performance] 1,1 max_performance_rank={iM-1} -rm[-1]
  --z[best_score] 1,1 max_best_score_rank={iM-1} -rm[-1]
  --z[average] 1,1 max_average_rank={iM-1} -rm[-1]
  --z[coffee_balance] 1,1 max_coffee_balance_rank={iM} -rm[-1]

  # Loop on each player row.
  -repeat @{rank,h}
    p=@{rank,(1,$>)}
    n=@{nb_games,(0,$p)}
    c={if(@{nb_games,(0,$p)}==0,0,v=@{score,(1,$p)};if(v>=1&&v<=3,v,if(v==$max_rank-1,4,if(v==$max_rank,5,0))))}
    i=@#

    # Rank.
    t_rank=@{score,(1,$p)}
    -_gpt_field $t_rank,48,$row_height,16,1,$c

    # Avatar.
    -if @{-path_tmp}/${player${p}_file} @{-path_tmp}/${player${p}_file}
    -else ${player${p}_url}${player${p}_file} -o[-1] @{-path_tmp}/${player${p}_file}
    -endif
    -to_rgb[-1] --[-1] 255 -rr2d[-1] {$row_height-2},{$row_height-2},2,2 -+[-1] 255 -frame[-1] 1,1,0

    # Name.
    t_name=@{-_gpt_rm_underscore\ ${player${p}_name}}

    0 -text[-1] $t_name,0,0,32,1,255,255,255
    -r[-1] 100%,100%,1,4
    -sh[-1] 0,2 -*[-1] '(2-c)*0.9*y/h' -rm[-1]
    -drop_shadow[-1] 1,1,1
    -_gpt_field " ",225,{1.5*$row_height},20,1,$c -mv[-1] -2
    -compose_alpha[-2,-1]
    -r2dy[-1] $row_height
    -z[-1] 1,1,{w-2},{h-2} -frame[-1] 1,1,0

    # Score.
    t_score=@{score,(0,$p)}
    -if {$t_score>0} t_score=+$t_score -endif
    -_gpt_field $t_score,80,$row_height,20,$n,$c

    # Chips [malus]
    t_chips=@{chips,(0,$p)}
    t_malus={-@{abs_malus,(0,$p)}}
    -if {$t_chips>0} t_chips=+$t_chips -endif
    -_gpt_field $t_chips\ [$t_malus],80,$row_height,16,$n,$c

    # Played
    t_nb_games=@{nb_games,(0,$p)}
    -_gpt_field $t_nb_games,48,$row_height,16,$n,$c

    # Won/lost.
    --lines[winners] $p
    t_won=@{-1,+}
    --lines[losers] $p
    t_lost=@{-1,+}
    -rm[-2,-1]
    -_gpt_field $t_won/$t_lost,48,$row_height,16,$n,$c

    # Trend.
    -if {!$n} {$row_height-2},{$row_height-2},1,3,255 -frame[-1] 1,1,0
    -else
      t_trend={-@{trend,(0,$p)}}
      -_gpt_field " ",128,128,16,$n,$c
      -if {$t_trend>0} t_trend=+$t_trend -j[-1] [arrow_up],0,0,0,0,1,[arrow_up_mask]
      -elif {$t_trend<0} -j[-1] [arrow_down],0,0,0,0,1,[arrow_down_mask]
      -else -j[-1] [arrow_eq],0,0,0,0,1,[arrow_eq_mask]
      -endif
      -r2dy[-1] $row_height

      -if $2
        -z[-1] 1,1,{w-2},{h-2} -frame[-1] 1,1,0
      -else
        -if {$t_trend>0} -_gpt_field "\n\n    "$t_trend,$row_height,$row_height,48,$n,0
        -elif {$t_trend<0} -_gpt_field "\n\n"$t_trend"     ",$row_height,$row_height,48,$n,0
        -else -_gpt_field " ",$row_height,$row_height,48,$n,0
        -endif
        -/[-1] 255 -*[-2,-1]
      -endif

    -endif

    # Statistics.
    -if {!$n} {if($2,2*$row_height,4*$row_height+2)},{$row_height},1,3,255
    -else
      {3*$row_height},{1.5*$row_height},1,3,255

      # Histogram of session ranks.
      --lines[ranks] $p,$p -histogram[-1] $max_players,1,$max_players
      -graph[-2] [-1],3,0,0,0,0.2,0,64,255
      -rm[-1]

      # Plot of results.
      --lines[scores] $p
      -discard[-1] -1 --[-1] 100 -cumul[-1] sa={ia} sm={im} sM={iM}
      -grid[-2] {max(20,100/max(1,h-1))}%,10,0,0,0.6,0xCCCCCCCC,0
      (0,0) -graph[-3] [-1],1,0,{$sM+10},{$sm-10},1,0 -rm[-1]
      ($sa,$sa) -graph[-3] [-1],1,0,{$sM+10},{$sm-10},1,0x55555555,0,150,0 -rm[-1]
      -graph[-2] [-1],2,0,{$sM+10},{$sm-10},1,255,32,48 -rm[-1]
      -r2dy[-1] {$row_height}

      # Pie-chart of sessions ranks.
      -if {!$2}
        1,$row_height,1,3,0        # Separator
        --lines[ranks] $p -histogram[-1] $max_players,1,$max_players -y[-1] y
        ip=@#
        (1,10,255,242,153)
        (2,10,222,222,222)
        (3,10,232,209,196)
        ({$max_players-1},10,255,204,204)
        ($max_players,10,255,153,153)
        -if {$max_players==1} -rm[-4--1]
        -elif {$max_players==2} -rm[-3--1]
        -elif {$max_players==3} -rm[-2--1]
        -elif {$max_players==4} -rm[-2]
        -elif {$max_players>5} -a[-3,-2] y -r[-2] 100%,{$max_players-3},1,1,3 -round[-2]
        -endif
        -a[$ip--1] y
        -j[-1] [-2],1,0 -rm[-2]

        256,256,1,3,255 -piechart[-1] 57,0,0,0,@-2,"abs.",{@{scores,w}-@{nb_games,(0,$p)}},255,255,255 -frame[-1] 10,10,255
        1,$row_height,1,3,0
        256,256,1,3,255 -piechart[-1] 57,0,0,0,@-4 -frame[-1] 10,10,255
        -rm[-4] -r2dy[-3,-1] $row_height
        -a[-5--1] x
      -endif

    -endif
    -z[-1] 1,1,{w-2},{h-2} -frame[-1] 1,1,0

    # Last score.
    t_last_score=@{scores,(100%,$p)}
    -if {$t_last_score==-1} t_last=abs.
    -else
      t_last_score={$t_last_score-100}
      -if {$t_last_score>0} t_last_score=+$t_last_score -endif
      t_last_rank=@{ranks,(100%,$p)}
      t_last=$t_last_score\ ($t_last_rank)
    -endif
    c={v=@{ranks,(100%,$p)};if(v>=1&&v<=3,v,if(v==@{nb_players,-1}-1,4,if(v==@{nb_players,-1},5,0)))}
    -_gpt_field $t_last,64,$row_height,16,$n,$c

    # Best score.
    t_best_score={v=@{best_score,(0,$p)};if(v==-1,-1,v)}
    t_best_rank=@{best_score,(1,$p)}
    -if {$t_best_score>0} t_best_score=+$t_best_score
    -elif {$t_best_score==-1} t_best_score=abs.
    -endif
    c={v=@{best_score,(1,$p)};if(v>=1&&v<=3,v,if(v==$max_best_score_rank-1,4,if(v==$max_best_score_rank,5,0)))}
    -_gpt_field $t_best_score\ ($t_best_rank),64,$row_height,16,$n,$c

    # Highest chips.
    t_highest_chips={v=@{highest_chips,(0,$p)};if(v==-1,-1,v)}
    t_highest_rank=@{highest_chips,(1,$p)}
    -if {$t_highest_chips>0} t_highest_chips=+$t_highest_chips
    -elif {$t_highest_chips==-1} t_highest_chips=abs.
    -endif
    c={v=@{highest_chips,(1,$p)};if(v>=1&&v<=3,v,if(v==$max_best_score_rank-1,4,if(v==$max_best_score_rank,5,0)))}
    -_gpt_field $t_highest_chips\ ($t_highest_rank),64,$row_height,16,$n,$c

    # Lowest chips.
    t_lowest_chips={v=@{lowest_chips,(0,$p)};if(v==-1,-1,v)}
    t_lowest_rank=@{lowest_chips,(1,$p)}
    -if {$t_lowest_chips>0} t_lowest_chips=+$t_lowest_chips
    -elif {$t_lowest_chips==-1} t_lowest_chips=abs.
    -endif
    c={v=@{lowest_chips,(1,$p)};if(v>=1&&v<=3,v,if(v==$max_performance_rank,4,if(v==$max_performance_rank+1,5,0)))}
    -_gpt_field $t_lowest_chips\ ($t_lowest_rank),64,$row_height,16,$n,$c

    # Performance.
    t_performance=@{performance,(0,$p)}
    t_performance_rank=@{performance,(1,$p)}
    c={v=@{performance,(1,$p)};if(v>=1&&v<=3,v,if(v==$max_performance_rank-1,4,if(v==$max_performance_rank,5,0)))}
    -_gpt_field $t_performance%\ ($t_performance_rank),64,$row_height,16,$n,$c

    # Average [std].
    --lines[scores] $p -discard[-1] -1
    t_average={if(i==-1,0,round(ia-100))}
    -if {$t_average>0} t_average=+$t_average -endif
    t_average_std={if(i==-1,0,round(sqrt(iv)))}
    -rm[-1]
    t_average_rank=@{average,(1,$p)}
    c={v=@{average,(1,$p)};if(v>=1&&v<=3,v,if(v==$max_average_rank-1,4,if(v==$max_average_rank,5,0)))}
    -_gpt_field $t_average\ [$t_average_std]\ ($t_average_rank),100,$row_height,16,$n,$c

    # Coffee balance.
    ({'{round(@{coffee_balance,(0,$p)},0.4)}'}) -z[-1] 0,3
    t_coffee_balance=@{-1,t}
    -rm[-1]
    -if {$t_coffee_balance>0} t_coffee_balance=+$t_coffee_balance -endif
    t_coffee_rank=@{coffee_balance,(1,$p)}
    c={v=@{coffee_balance,(1,$p)};if(v>=1&&v<=3,v,if(v==$max_coffee_balance_rank-1,4,if(v==$max_coffee_balance_rank,5,0)))}
    -_gpt_field $t_coffee_balance\$\ ($t_coffee_rank),80,$row_height,16,$n,$c

    # Append all fields into a single row.
    -if {!$n} -f[$i,{$i+2}--1] "i*(0.7+0.3*(((x+y)%8)!=0))" -endif  # Add hatches for absent player.
    -a[$i--1] x

  -done

  # Title.
  avg_nb_players={round(@{nb_players,a},0.5)}
  -if {$2==0} t_title="** GREYC Poker Tour ** Session \#"@{scores,w}"   (avg. \#player = "$avg_nb_players")"
  -elif {$2>0} t_title="** GREYC Poker Tour ** Last "@{scores,w}" sessions  (avg. \#player = "$avg_nb_players")"
  -else t_title="** GREYC Poker Tour ** Session \#"@{scores,w}"/"{-$2}" (avg. \#player = "$avg_nb_players")"
  -endif
  1 -text[-1] $t_title,0,0,57,1,255 -r[-1] 100%,100%,1,4 -drop_shadow[-1] 5,5,2
  -r2dy[-1] 24 -r[-1] {@{$board,w}-2},{1.5*$row_height-2},1,4,0,0,0.5,{if($2,0.9,0.6)}
  -i[-2] 1,3,1,3,32,0,64,32,64,128,64,200,256 -r[-2] [-1],[-1],1,3,3 -compose_rgba[-2,-1]
  -if {$2>0} -shift[-1] 0,0,0,1,2 -elif {$2<0} -mirror[-1] c -endif
  -frame[-1] 1,1,0
  -mv[-1] $board

  # Session winner(s).
  -if {!$2}
    --columns[scores] 100% --f[-1] y -a[-2,-1] x -sort[-1] -,y
    -f[-1] 'if(i(0,y)==i(0,0),i,-1)' -autocrop[-1] -1 -nm[-1] session_winners # Keep only winners.
    nb_session_winners={h}
    t_session_winners=""
    -repeat $nb_session_winners
      i=@{session_winners,(1,$>)}
      t_session_winners=${player${i}_name}"__"${t_session_winners}
      @{-path_tmp}/${player{@{session_winners,(1,$>)}}_file} --[-1] 255 -rr2d[-1] 56,56,2,2 -+[-1] 255 -frame[-1] 1,1,0
    -done
    t_session_winners=@{-_gpt_rm_underscore\ $t_session_winners}
    1 -text[-1] "Session winner"@{-if\ {$nb_session_winners==1}\ -u\ \"\"\ -else\ -u\ s\ -endif}" : "$t_session_winners,0,0,57,1,255
    -r[-1] 100%,100%,1,4 -drop_shadow[-1] 5,5,2
    -r2dy[-1] 24 -r[-1] {@{$board,w}-2},{1.5*$row_height-2},1,4,0,0,0.1,0.5
    -i[-2] 1,2,1,3,0,128,128,255,64,128 -r[-2] [-1],[-1],1,3,3 -compose_rgba[-2,-1]
    -if {$2>0} -shift[-1] 0,0,0,1,2 -elif {$2<0} -mirror[-1] c -endif
    -repeat $nb_session_winners -j[-1] [{-2-$<}],{w-64-$>*64},7 -done
    -frame[-1] 1,1,0
    -mv[-1] {$board+1}
    -rm[-{$nb_session_winners+1}--1]
  -endif

  # Session loser(s).
  -if {!$2}
    --columns[losers] 100% --f[-1] y -a[-2,-1] x -sort[-1] -,y
    -f[-1] 'if(i(0,y),i,-1)' -autocrop[-1] -1 -nm[-1] session_losers # Keep only losers.
    nb_session_losers={h}
    t_session_losers=""
    -repeat $nb_session_losers
      i=@{session_losers,(1,$>)}
      t_session_losers=${player${i}_name}"__"${t_session_losers}
      @{-path_tmp}/${player{@{session_losers,(1,$>)}}_file} --[-1] 255 -rr2d[-1] 56,56,2,2 -+[-1] 255 -frame[-1] 1,1,0
    -done
    t_session_losers=@{-_gpt_rm_underscore\ $t_session_losers}
    1 -text[-1] "Session loser"@{-if\ {$nb_session_losers==1}\ -u\ \"\"\ -else\ -u\ s\ -endif}" : "$t_session_losers,0,0,57,1,255
    -r[-1] 100%,100%,1,4 -drop_shadow[-1] 5,5,2
    -r2dy[-1] 24 -r[-1] {@{$board,w}-2},{1.5*$row_height-2},1,4,0,0,0.1,0.5
    -i[-2] 1,2,1,3,128,255,0,128,64,128 -r[-2] [-1],[-1],1,3,3 -compose_rgba[-2,-1]
    -if {$2>0} -shift[-1] 0,0,0,1,2 -elif {$2<0} -mirror[-1] c -endif
    -repeat $nb_session_losers -j[-1] [{-2-$<}],{w-64-$>*64},7 -done
    -frame[-1] 1,1,0
    -rm[-{$nb_session_losers+2}--2]
  -endif

  # Append rows together.
  -a[$board--1] y

  # Add final shadow.
  100%,100%,1,1,255 -a[-2,-1] c -drop_shadow[-1] 6,6,4 -i[-2] {w},{h},1,3,255 -compose_alpha[-2,-1]

  # Quit properly.
  -k[$board] -v +

_gpt_rm_underscore :
  ({'"$1"'}) -replace[-1] {'_'},{'\ '} -u @{-1,t} -rm[-1]

# $1 : Text - $2 : Width - $3 : Height - $4 : Font size - $5 : Text - $6 : Color code.
_gpt_field :
  -if {!$5} {$2-2},{$3-2},1,3,255 -frame[-1] 1,1,0 -return -endif
  1 -text[-1] "$1",0,0,57,1,1 -*[-1] -1 -+[-1] 1
  -r2dy[-1] $4 --[-1] 1 -r[-1] {$2-2},{$3-2},1,1,0,0,0.5,0.5 -+[-1] 1
  -frame[-1] 1,1,0
  [-1]x2
  -if {$6==1} -*[-3] 255 -*[-2] 242 -*[-1] 153
  -elif {$6==2} -*[-3] 222 -*[-2] 222 -*[-1] 222
  -elif {$6==3} -*[-3] 232 -*[-2] 209 -*[-1] 196
  -elif {$6==4} -*[-3] 255 -*[-2] 204 -*[-1] 204
  -elif {$6==5} -*[-3] 255 -*[-2] 153 -*[-1] 153
  -elif {$6==6} -*[-3] 240 -*[-2] 240 -*[-1] 240
  -else -*[-3--1] 255
  -endif
  -a[-3--1] c

#--------------------------
#
# Define menu entries
# for the GIMP plug-in.
#
#--------------------------

# Update function called each time the G'MIC plug-in for GIMP has refreshed his filters
# (by function 'update_filter(const bool)' in gmic_gimp.cpp.
# Parameter $1 can be equal to { 0=no_network_update | 1=network_update }.
# This function is always called with $1==0 when the plug-in is launched.
gimp_update_filters : -skip $*
  gmic_path=$GMIC_GIMP_PATH
  -if {!narg($gmic_path)} gmic_path=@{-path_user}/ -endif
  -if {!@{-is_windows}} gmic_path=${gmic_path}. -endif
  gmic_path=${gmic_path}gmic_sources.cimgz
  -if $gmic_path -else -gimp_add_filter_sources 1 -endif

# Generate a splitted preview, with arguments "command",_split_type={ 0=full | 1=forw. horiz. | 2=forw. vert. | 3=back. horiz. | 4=back. vert. }
_before :
  33,11 -text[-1] "Before",1,-1,13,1,1
_after :
  26,11 -text[-1] "After",1,-1,13,1,1

gimp_split_preview :
  -repeat @#
    -if {$2==0} -e[] "$1" -l[-1] $1 -endl -mv[-1] 0 -continue -endif  # No split.
    -if {!($2%2)} # Vertical split.
      -s[-1] x,2
      -if {$2==2} -l[-1] $1 -endl -to_colormode[-2,-1] {max(@{-2,s},s)} -_before -_after
      -else -l[-2] $1 -endl -to_colormode[-2,-1] {max(@{-2,s},s)} -_after -_before
      -endif
      -line[-3] 0,0,0,@{-3,h},1,0,0,0,255 -a[-4,-3] x
    -else # Horizontal split.
      -s[-1] y,2
      -if {$2==1} -l[-1] $1 -endl -to_colormode[-2,-1] {max(@{-2,s},s)} -_before -_after
      -else -l[-2] $1 -endl -to_colormode[-2,-1] {max(@{-2,s},s)} -_after -_before
      -endif
      -line[-3] 0,0,@{-3,w},0,1,0,0,0,255 -a[-4,-3] y
    -endif
    --dilate[-2,-1] 3 -*[-4,-3] 255 -to_colormode[-4,-3] @{-5,s} # If splited, display "before/after" text.
    -j[-5] [-4],1,1,0,0,0.8,[-2] -j[-5] [-3],{@{-5,w}-w-1},{@{-5,h}-h-1},0,0,0.8,[-1]
    -rm[-4--1]
  -mv[-1] 0 -done

# Generate a 'no-preview' image.
gimp_no_preview :
  -_gimp_no_preview "No preview\navailable","$*"

_gimp_no_preview :
  -if {@#>0} -k[0] -else 256,256,1,1,128 -endif
  118,50 -text[-1] "$1",2,1,24,1,255 -r[-1] [-2],[-2],1,1,0,0,0.5,0.5 -to_colormode[-1] @{-2,s}
  (1.5,0,1.5;0,0,0;1.5,0,1.5) -r[-1] [-3],3 -*[-3,-1] -c[-2] 0,255 -or
  -skip "$*"


# Do not forget to ucomment this entry for a deprecated version of the G'MIC plug-in !
# #@gimp <span foreground="red"><b>  UPDATE INFORMATION</b></span> : _none_, gimp_logo_en
# #@gimp : note = note{"A <b>new version</b> of the G'MIC plug-in for GIMP is available !
# #@gimp : You are strongly encouraged to download and install this updated version, by clicking on one of the following urls :"}
# #@gimp : note = note{"\n<span foreground="purple"><u>Windows version :</u></span>"}
# #@gimp : url = link{"Download G'MIC plug-in for Windows (32 bits)","http://downloads.sourceforge.net/gmic/gmic_gimp_win32.exe"}
# #@gimp : note = note{"<b>Installation </b>: unzip the archive files and copy them into folder\n
# #@gimp :              <i>C:\\Program Files\\GIMP\\lib\\gimp\\2.0\\plug-ins\</i>"}
# #@gimp : note = note{"\n<span foreground="purple"><u>Linux version :</u></span>"}
# #@gimp : url = link{"Download plug-in for Linux (32 bits)","http://downloads.sourceforge.net/gmic/gmic_gimp_linux32.zip"}
# #@gimp : url = link{"Download plug-in for Linux (64 bits)","http://downloads.sourceforge.net/gmic/gmic_gimp_linux64.zip"}
# #@gimp : note = note{"<b>Installation </b>: unzip the archive files and copy them in folder\n
# #@gimp :              <i>/usr/lib/gimp/2.0/plug-ins/</i>"}
# #@gimp : note = note{"\nNote that there will be no updated filters anymore for your current plug-in version.
# #@gimp : Installing the G'MIC plug-in for GIMP is easy and fast, so there are no reasons not for doing it :).\n\n
# #@gimp : Best regards,\n\n <i>The G'MIC team.</i>"}



#----------------------
# English translations
#----------------------

#@gimp_en <i>About</i>
#----------------------

#@gimp_en G'MIC for GIMP : _none_, gimp_logo_en
#@gimp_en : note = note{"
#@gimp_en : <span foreground="purple">( <b>G</b>REYC's <b>M</b>agic <b>I</b>mage <b>C</b>onverter )</span>\n\nis proposed to you by"}
#@gimp_en : note = link("David Tschumperl\303\251","http://www.greyc.ensicaen.fr/~dtschump")
#@gimp_en : note = link{"( IMAGE Team / GREYC Laboratory - CNRS UMR 6072 )","http://www.greyc.ensicaen.fr/EquipeImage"}
#@gimp_en : note = note{"
#@gimp_en : This plug-in is based on our open-source libraries <b>G'MIC</b> and <b>CImg</b> (C++ Template Image Processing Library),
#@gimp_en : available at :"}
#@gimp_en : note = link("http://gmic.sourceforge.net/")
#@gimp_en : note = note{"and"}
#@gimp_en : note = link("http://cimg.sourceforge.net/")
#@gimp_en : note = note{"\n
#@gimp_en : If you appreciate <b>G'MIC</b>, you are welcome to send us a nice postcard from your place, at :\n\n
#@gimp_en : <small><tt>David Tschumperl&#233;,\n Laboratoire GREYC (CNRS UMR 6072), Equipe Image,\n
#@gimp_en :  6 Bd du Mar&#233;chal Juin,\n 14050 Caen Cedex / France.</tt></small>\n\n
#@gimp_en : Postcards senders automatically enter the <i>Friends Hall of Fame</i> :) !
#@gimp_en : "}
gimp_logo : -skip "${1=Plug-in for GIMP}"
  -if @# -k[0] -endif
  1 -text[-1] "G'MIC",0,0,57,1,1 -label[-1] 0
  6,1,1,3 -rand[-1] 150,255 -point[-1] 0 -map[-2] [-1] -rm[-1]
  -expand_xy[-1] 10,0 -b[-1] 2 -r[-1] 200%,200%,1,3,6 -sqr[-1] -c[-1] 0,60% -n[-1] 0,255
  -warp_perspective[-1] 0.5,0,1,50,50,0 -shift[-1] 0,-10
  100%,100% -noise[-1] 0.8,2 -*[-1] 180 --blur_linear[-1] 20,0,45,0 -*[-1] 20 -max[-3--1]
  -sh[-1] 2,2 (0;128) -r[-1] [-2],3 -+[-2,-1] -min[-1] 255 -rm[-1]
  -text_outline[-1] "$1",32%,75%,13,3,1,255 -frame[-1] 1,1,128 -mv[-1] 0
  -if {@#>1} -*[1--1] 0.45 -repeat {@#-1} -j[-1] [0],{(w-@{0,w})/2},{(h-@{0,h})/2} -mv[-1] 1 -done -rm[0] -endif

gimp_logo_old :
  -if @# ratio={w/h} -else ratio=1 -endif
  -rm 118,44,1,1 -text "G'MIC",3,-6,57,1,255 -r 100%,100%,10,1 -r 100%,100%,20,1,0,0,0.5,0.5,0.5 -b 1.5
  -isosurface3d 50%
  -col3d {?(150,255)},{?(150,255)},{?(150,255)}
  -sphere3d 8 -col3d[-1] {?(150,255)},{?(150,255)},{?(150,255)} -+3d[-1] 72,-6 -+3d -c3d[-1] -rv3d
  -db3d 0 -m3d 4 -sl3d 0.2 -ss3d 1.3 -r3d[-1] 1,0,0,30 -f3d 120 -*3d[-1] 1.5
  230,120,1,3 -object3d[-1] [-2],50%,30%,0,1 -rm[-2] -text "$1",12%,75%,24,1,255
  -to_rgba -replace_color 0,0,0,0,0,255,0,0,0,0 -drop_shadow 6,6,2
  -i[-2] @{"-fitratio_wh 230,120,"$ratio},1,3
  -rand[-2] 0,255 -sh[-2] 0,0 -/[-1] 2 -rm[-1]
  -blur_radial[-2] 10 -sharpen[-2] 600
  -r[-1] [-2],[-2],1,4,0,0,0.5,0.5 -compose_alpha

gimp_logo_en :
  -gimp_logo "Plug-in for GIMP"

#@gimp_en Filters design : _none_, _none_
#@gimp_en : note = note{"
#@gimp_en : <b>G'MIC</b> is an <b>open</b> image processing framework. Thus, including
#@gimp_en : <b>user-defined filters</b> into this plug-in is possible.\n\n
#@gimp_en : To do so, you need to create a <span foreground="purple" style="italic">.gmic</span>
#@gimp_en : file in your <i>Home</i> folder (or <i>Applications Data/</i> on Windows, without the first dot).
#@gimp_en : It will be read each time the plug-in is launched, or when the <i>Refresh</i>
#@gimp_en : button (under the central pane) is pressed. It must be a regular ASCII file, containing the declarations and
#@gimp_en : implementations of the filters (written in the <b>G'MIC</b> language) that will be added
#@gimp_en : to the list of available ones.\n\n
#@gimp_en : Existing filters are already defined this way.
#@gimp_en : The current implementations can be seen at :"}
#@gimp_en : note = link("http://gmic.sourceforge.net/gmic_def.xxxx")
#@gimp_en : note = note{"
#@gimp_en : Writting a new filter in <b>G'MIC</b> is not particularly awful and
#@gimp_en : can be generally done in very few lines.\n\n
#@gimp_en : <span foreground="purple" underline="single">Example of a valid <i>.gmic</i> entry :</span>\n\n
#@gimp_en : <tt>#@gimp My effect : my_effect, my_effect\n
#@gimp_en : #@gimp : Sigma = float(2,0,10)\n
#@gimp_en : my_effect :\n     --blur $1 -n 0,255 -xor</tt>\n\n
#@gimp_en : By the way, you are encouraged to share your nice custom filters on the dedicated forum,
#@gimp_en : for inclusion into next releases of <b>G'MIC</b> :
#@gimp_en : "}
#@gimp_en : note = link("Go to the G'MIC forum","http://www.flickr.com/groups/gmic/discuss/")

#@gimp_en Filters update : _none_, _none_
#@gimp_en : note = note{"
#@gimp_en : Thanks to its openness, <b>G'MIC</b> is able to <b>update</b> his list of filters
#@gimp_en : from the Internet. Pushing the <i>Refresh</i> button (under the central pane)
#@gimp_en : makes <b>G'MIC</b> connect to the update server and download the latest filter definitions.
#@gimp_en : Technically speaking, this update procedure creates/replaces the file
#@gimp_en : <span foreground="purple" style="italic">.gmic_def.xxxx</span> in your <i>Home</i> folder
#@gimp_en : (or <i>Application Data/</i> on Windows, without the first dot),
#@gimp_en : where <i>xxxx</i> are the four digits of the <b>G'MIC</b> version number.
#@gimp_en : In case of connecting troubles, you can then manually do the update by retrieving the filter
#@gimp_en : definition file directly from :"}
#@gimp_en : note = link("http://gmic.sourceforge.net/gmic_def.xxxx")
#@gimp_en : note = note{"
#@gimp_en : Just copy and rename this file as your <span foreground="purple" style="italic">.gmic_def.xxxx</span>
#@gimp_en : (replace the <i>xxxx</i> by the 4 digits of your <b>G'MIC</b> version number)
#@gimp_en : and you are done.
#@gimp_en : By the way, deleting this file resets all the filters to their initial state.
#@gimp_en : "}

#---------------------
# French translations
#---------------------

#@gimp_fr <i> &#192; propos</i>
#------------------------------

#@gimp_fr G'MIC pour GIMP : _none_, gimp_logo_fr
#@gimp_fr : note = note{"
#@gimp_fr : <span foreground="purple">( <b>G</b>REYC's <b>M</b>agic <b>I</b>mage <b>C</b>onverter )</span>\n\nvous est proposé par"}
#@gimp_fr : note = link("David Tschumperl\303\251","http://www.greyc.ensicaen.fr/~dtschump")
#@gimp_fr : note = link{"( Equipe IMAGE / Laboratoire GREYC - CNRS UMR 6072 )","http://www.greyc.ensicaen.fr/EquipeImage"}
#@gimp_fr : note = note{"
#@gimp_fr : Ce greffon est bas&#233; sur nos biblioth&#232;ques libres <b>G'MIC</b> et <b>CImg</b> (C++ Template Image Processing Library),
#@gimp_fr : disponibles aux adresses :"}
#@gimp_fr : note = link("http://gmic.sourceforge.net/")
#@gimp_fr : note = note{"et"}
#@gimp_fr : note = link("http://cimg.sourceforge.net/")
#@gimp_fr : note = note{"\n
#@gimp_fr : Si vous appr&#233;ciez <b>G'MIC</b>, vous pouvez nous le faire savoir en nous envoyant une jolie carte
#@gimp_fr : postale de votre ville ou r&#233;gion, &#224; l'adresse :\n\n
#@gimp_fr : <small><tt>David Tschumperl&#233;,\n Laboratoire GREYC (CNRS UMR 6072), Equipe Image,\n
#@gimp_fr :  6 Bd du Mar&#233;chal Juin,\n 14050 Caen Cedex / France.</tt></small>\n\n
#@gimp_fr : Envoyer une carte postale vous fera rentrer <i>de facto</i> dans le <i>Friends Hall of Fame</i> :) !
#@gimp_fr : "}
gimp_logo_fr :
  -gimp_logo "Greffon pour GIMP"

#@gimp_fr Cr&#233;ation de filtres : _none_, _none_
#@gimp_fr : note = note{"
#@gimp_fr : <b>G'MIC</b> est un système <b>ouvert</b> de traitement d'image. Il est ainsi possible
#@gimp_fr : d'ajouter vos <b>propres filtres personnalisés</b> à l'intérieur même de ce greffon.\n\n
#@gimp_fr : Pour cela, il vous suffit de cr&#233;er un fichier <span foreground="purple" style="italic">.gmic</span>
#@gimp_fr : dans votre dossier <i>Home</i> (ou <i>Applications Data/</i> sous Windows, sans le premier point).
#@gimp_fr : Ce fichier va être lu &#224; chaque d&#233;marrage du greffon, ou lorsque le bouton <i>Actualiser</i>
#@gimp_fr : (sous le panneau central) sera cliqu&#233;. Ce fichier ASCII va contenir les déclarations et les
#@gimp_fr : implémentations des filtres (écrits en langage <b>G'MIC</b>) qui vont s'ajouter à la liste des filtres disponibles.\n\n
#@gimp_fr : Tous les filtres existants sont déjà définis de cette façon. Les impl&#233;mentations actuelles sont visibles
#@gimp_fr : &#224; l'adresse :"}
#@gimp_fr : note = link("http://gmic.sourceforge.net/gmic_def.xxxx")
#@gimp_fr : note = note{"
#@gimp_fr : Ecrire un filtre en langage <b>G'MIC</b> n'est pas particulièrement difficile (sans être trivial),
#@gimp_fr : et ne n&#233;cessite souvent que quelques lignes.\n\n
#@gimp_fr : <span foreground="purple" underline="single">Exemple de fichier <i>.gmic</i> valide :</span>\n\n
#@gimp_fr : <tt>#@gimp My effect : my_effect, my_effect, Sigma = float(2,0,10)\n
#@gimp_fr : my_effect :\n     --blur $1 -n 0,255 -xor</tt>\n\n
#@gimp_fr : Vous &#234;tes bien s&#251;r encourag&#233;s &#224; partager vos propres filtres sur le forum pr&#233;vu &#224;
#@gimp_fr : cet effet, pour une inclusion éventuelle dans les prochaines versions de <b>G'MIC</b> :
#@gimp_fr : "}
#@gimp_fr : note = link("Participer au forum G'MIC","http://sourceforge.net/projects/gmic/forums/forum/849382")

#@gimp_fr Mise &#224; jour des filtres : _none_, _none_
#@gimp_fr : note = note{"
#@gimp_fr : De par son architecture ouverte, <b>G'MIC</b> est capable de <b>mettre &#224; jour</b> sa liste
#@gimp_fr : de filtres. L'appui sur le bouton <i>Actualiser</i> (sous le panneau central)
#@gimp_fr : va permettre la connexion au serveur de mises &#224; jour, et le t&#233;l&#233;chargement
#@gimp_fr : des derni&#232;res d&#233;finitions de filtres. C'est la seule op&#233;ration r&#233;seau
#@gimp_fr : que nous avons autoris&#233;e dans <b>G'MIC</b>.\n\n
#@gimp_fr : Techniquement, cette proc&#233;dure cr&#233;&#233;/remplace le fichier
#@gimp_fr : <span foreground="purple" style="italic">.gmic_def.xxxx</span> dans votre r&#233;pertoire <i>Home</i>
#@gimp_fr : (ou <i>Application Data/</i> sous Windows, sans le premier point),
#@gimp_fr : o&#249; <i>xxxx</i> sont les quatres chiffres du num&#233;ro de version du greffon <b>G'MIC</b>.
#@gimp_fr : En cas de probl&#232;me, vous pouvez donc toujours mettre &#224; jour vos filtres manuellement,
#@gimp_fr : en t&#233;l&#233;chargeant le fichier suivant :"}
#@gimp_fr : note = link("http://gmic.sourceforge.net/gmic_def.xxxx")
#@gimp_fr : note = note{"
#@gimp_fr : Copiez juste ce fichier &#224; la bonne place, et renommez le en <span foreground="purple" style="italic">.gmic_def.xxxx</span>
#@gimp_fr : (remplacez les <i>xxxx</i> par le num&#233;ro de version de votre greffon <b>G'MIC</b>)
#@gimp_fr : et la proc&#233;dure de mise &#224; jour sera effectu&#233;e.
#@gimp_fr : Bien entendu, effacer ce fichier réinitialise l'ensemble des d&#233;finitions des filtres &#224; leurs &#233;tats initiaux.
#@gimp_fr : "}

#----------------------
# Catalan translations
#----------------------

#@gimp_ca <i> About</i>
#----------------------

#@gimp_ca G'MIC per al GIMP : _none_, gimp_logo_ca
#@gimp_ca : note = note{"
#@gimp_ca : <span foreground="purple">( <b>G</b>REYC's <b>M</b>agic <b>I</b>mage <b>C</b>onverter )</span>\n\n &#233;s una gentilesa de"}
#@gimp_ca : note = link("David Tschumperl\303\251","http://www.greyc.ensicaen.fr/~dtschump")
#@gimp_ca : note = link{"( IMAGE Team / GREYC Laboratory - CNRS UMR 6072 )","http://www.greyc.ensicaen.fr/EquipeImage"}
#@gimp_ca : note = note{"
#@gimp_ca : Aquest connector est&#224; basat en les biblioteques de codi obert <b>G'MIC</b> i <b>CImg</b> (C++ Template Image Processing Library),
#@gimp_ca : disponibles a :"}
#@gimp_ca : note = link("http://gmic.sourceforge.net/")
#@gimp_ca : note = note{"i"}
#@gimp_ca : note = link("http://cimg.sourceforge.net/")
#@gimp_ca : note = note{"\n
#@gimp_ca : Si t'agrada el <b>G'MIC</b>, pots enviar-nos una postal del lloc on vius, a :\n\n
#@gimp_ca : <small><tt>David Tschumperl&#233;,\n Laboratoire GREYC (CNRS UMR 6072), Equipe Image,\n
#@gimp_ca :  6 Bd du Mar&#233;chal Juin,\n 14050 Caen Cedex / France.</tt></small>\n\n
#@gimp_ca : Tot aquell que envi&#239; una postal apareixer&#224; al <i>Friends Hall of Fame</i> :) !
#@gimp_ca : "}
gimp_logo_ca :
  -gimp_logo "  per al GIMP"

#@gimp_ca Filters design : _none_, _none_
#@gimp_ca : note = note{"
#@gimp_ca : Si voleu podeu afegir els vostres <b>filtres d'usuari</b> al connector <b>G'MIC</b> :\n\n
#@gimp_ca : Per a fer-ho, cal que creeu un fitxer <span foreground="purple" style="italic">.gmic</span> (no oblideu el primer punt !)
#@gimp_ca : a la vostra <i>Carpeta d'inici</i> (o a la carpeta <i>Application Data</i> al Windows).
#@gimp_ca : El connector el llegir&#224; cada vegada que s'arranqui, o quan premeu el bot&#243; <i>Actualitzar els filtres</i>.
#@gimp_ca : Aquest fitxer ha de ser un arxiu de command del <b>G'MIC</b>, i ha de contindre les definicions de filtre
#@gimp_ca : que han d'apar&#232;ixer a la llista de filtres.
#@gimp_ca : Podeu veure un exemple d'un arxiu d'aquesta mena a :"}
#@gimp_ca : note = link("http://gmic.sourceforge.net/gmic_def.xxxx")
#@gimp_ca : note = note{"
#@gimp_ca : Escriure un nou filtre amb el llenguatge <b>G'MIC</b> no &#233;s trivial del tot (per&#242; tampoc una cosa inabastable), per&#242;
#@gimp_ca : normalment es pot fer en unes quantes l&#237;nies.\n\n
#@gimp_ca : <span foreground="purple" underline="single">Example d'un fitxer <i>.gmic</i> v&#224;lid :</span>\n\n
#@gimp_ca : <tt>#@gimp My effect : my_effect, my_effect, Sigma = float(2,0,10)\n
#@gimp_ca : my_effect :\n  --blur $1 -n 0,255 -xor</tt>\n\n
#@gimp_ca : Per cert, us encoratgem a que compartiu els vostres filtres personalitzats al f&#242;rum espec&#237;fic de <b>G'MIC</b> :
#@gimp_ca : "}
#@gimp_ca : note = link("Enlla\303\247a al f\303\262rum G'MIC","http://sourceforge.net/projects/gmic/forums/forum/849382")

#@gimp_ca Filters update : _none_, _none_
#@gimp_ca : note = note{"
#@gimp_ca : El connector <b>G'MIC</b> &#233;s capa&#231; d'<b>actualitzar</b> la seva llista de definicions de filtres
#@gimp_ca : des d'Internet. Prement el bot&#243; <i>Actualitzar els filtres</i> al plaf&#243; de l'esquerra
#@gimp_ca : fa que <b>G'MIC</b> es connecti amb el servidor d'actualitzacions
#@gimp_ca : i que descarregui les darreres definicions de filtres disponibles.\n\n
#@gimp_ca : B&#224;sicament, aquest procediment crea un fitxer
#@gimp_ca : <span foreground="purple" style="italic">.gmic_def.xxxx</span> a la vostra <i>Carpeta d'inici</i>
#@gimp_ca : (o a la carpeta <i>Application Data</i> a Windows),
#@gimp_ca : on <i>xxxx</i> s&#243;n els quatre d&#237;gits de la versi&#243; del connector <b>G'MIC</b>.
#@gimp_ca : En cas que tingueu problemes, podeu actualitzar manualment els vostres filtres, baixant-vos el fitxer d'actualitzaci&#243; des de:"}
#@gimp_ca : note = link("http://gmic.sourceforge.net/gmic_def.xxxx")
#@gimp_ca : note = note{"
#@gimp_ca : Llavors, nom&#233;s cal que copieu i canvieu el nom d'aquest fitxer com a <span foreground="purple" style="italic">.gmic_def.xxxx</span>
#@gimp_ca : (no oblideu el primer punt, i substitu&#239;u <i>xxxx</i> per el n&#250;mero de versi&#243; del vostre <b>G'MIC</b>)
#@gimp_ca : i ja est&#224;!
#@gimp_ca : Per cert, si esborreu aquest fitxer, tornareu a establir les definicions de filtres originals.
#@gimp_ca : "}

#----------------------
# Untranslated filters
#----------------------

#@gimp Release notes : _none_, _none_
#@gimp : note = note{"
#@gimp : - <b>2009/01/13</b> : version <i>1.3</i> (Initial).\n
#@gimp : - <b>2010/09/03</b> : version <i>1.4</i>.\n
#@gimp : - <b>2010/12/17</b> : version <i>1.4.7</i>.\n
#@gimp : - <b>2011/03/15</b> : version <i>1.4.8.3</i>.\n
#@gimp : - <b>2011/04/01</b> : version <i>1.4.9</i>.\n
#@gimp : - <b>2011/06/08</b> : version <i>1.4.9.5</i>.\n
#@gimp : - <b>2011/07/07</b> : version <i>1.5.0.0</i>.\n
#@gimp : - <b>2012/03/01</b> : version <i>1.5.1.0</i>.\n
#@gimp : - <span foreground="purple"><b>2012/05/10</b> : version <i>1.5.1.3</i> (Current stable).</span>\n
#@gimp : "}
#@gimp : link = link("View latest changelog","http://www.flickr.com/groups/gmic/discuss/72157629528183074/")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2012/05/10</i>.</small>")

#@gimp Contributors : _none_, _none_
#@gimp : note = note{"
#@gimp : We would like to thank all these people who contributed to <b>G'MIC</b> in one way or another.
#@gimp : A big hug to : \n\n
#@gimp : <b> -</b> <i>S&#233;bastien Fourey</i> <small>(code of ZArt)</small>
#@gimp : <b> -</b> <i>Aur&#233;lien Ceyden</i> <small>(packaging)</small>
#@gimp : <b> -</b> <i>Claude Bulin</i> <small>(packaging)</small>
#@gimp : <b> -</b> <i>Partha Bagchi</i> <small>(packaging)</small>
#@gimp : <b> -</b> <i>Roberto Ferramosca</i> <small>(packaging)</small>
#@gimp : <b> -</b> <i>Karsten Rodenacker</i> <small>(packaging &amp; filters)</small>
#@gimp : <b> -</b> <i>Bernd Zeimetz</i> <small>(packaging)</small>
#@gimp : <b> -</b> <i>J&#233;rome Ferrari</i> <small>(testing &amp; tutorials)</small>
#@gimp : <b> -</b> <i>Tom Keil</i> <small>(testing &amp; filters &amp; tutorials)</small>
#@gimp : <b> -</b> <i>Andy Kelday</i> <small>(testing &amp; filters)</small>
#@gimp : <b> -</b> <i>PhotoComiX</i> <small>(testing &amp; translation &amp; filters)</small>
#@gimp : <b> -</b> <i>Gentlemanbeggar</i> <small>(filters)</small>
#@gimp : <b> -</b> <i>Arto Huotari</i> <small>(filters)</small>
#@gimp : <b> -</b> <i>Iain Fergusson</i> <small>(filters)</small>
#@gimp : <b> -</b> <i>Fran&#231;ois Collard</i> <small>(testing)</small>
#@gimp : <b> -</b> <i>Angelo Lama</i> <small>(testing)</small>
#@gimp : <b> -</b> <i>Claes Holmerson</i> <small>(tutorials)</small>
#@gimp : <b> -</b> <i>Mauro Quercia</i> <small>(translation)</small>
#@gimp : <b> -</b> <i>Stepanekos</i> <small>(translation)</small>
#@gimp : <b> -</b> <i>Dani Sard&#224;</i> <small>(translation)</small>
#@gimp : <b> -</b> <i>Mark</i> <small>(translation)</small>
#@gimp : <b> -</b> <i>Guilherme Razgriz</i> <small>(translation)</small>
#@gimp : <b> -</b> <i>Yuri Shemanin</i> <small>(debugging)</small>
#@gimp : <b> -</b> <i>St&#233;phane de la Linuxerie</i> <small>(design)</small>
#@gimp : <b> -</b> <i>Mahvin</i> <small>(testing &amp; corrections)</small>
#@gimp : <b> -</b> <i>The GIMP users at Flickr</i> <small>(testing &amp; suggestions)</small>
#@gimp : <b> -</b>"}
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2011/03/30</i>.</small>")

#@gimp Friends Hall of Fame : _none_, gimp_friends
#@gimp : note = note{"\n<span foreground="purple" underline="single">Donators :</span>"}
#@gimp : note = note{" <b>-</b> We've received <b>4</b> donations from <b>G'MIC</b> mega-enthusiasts so far.
#@gimp :               You could be the 5th donator :)"}
#@gimp : note = note{" <b>-</b> A big hug goes to these folks (recently received first) :"}
#@gimp : link = link(0,"[1] Eddy Vervest","http://www.flickr.com/people/twekkel/")
#@gimp : link = link(0,"[2] Steven Shupe","http://www.flickr.com/photos/ssshupe/")
#@gimp : link = link(0,"[3] Flavio Casadei Della Chiesa","http://www.flaviocdc.net/wiki/")
#@gimp : link = link(0,"[4] Lyle Kroll","http://www.artwanted.com/artist.cfm?artid=10918")
#@gimp : sep = separator()
#@gimp : note = note{"\n<span foreground="purple" underline="single">Postcard senders :</span>"}
#@gimp : note = note{" <b>-</b> We've received <b>14</b> postcards from <b>G'MIC</b> enthusiasts so far.
#@gimp :               You could be the 15th sender :)"}
#@gimp : note = note{" <b>-</b> A big hug goes to these folks (recently received first) :"}
#@gimp : link = link(0,"[1] Werner Meier - Mettlach/Germany","http://cimg.sourceforge.net/img/postcard37.jpg")
#@gimp : link = link(0,"[2] Arto Huotari - Helsinki/Finland","http://cimg.sourceforge.net/img/postcard36.jpg")
#@gimp : link = link(0,"[3] Benoit Gauzere - California/USA","http://cimg.sourceforge.net/img/postcard33.jpg")
#@gimp : link = link(0,"[4] Arkadi Gelfond - Foster City - California/USA","http://cimg.sourceforge.net/img/postcard30.jpg")
#@gimp : link = link(0,"[5] Corinne Masimann - Neuchatel/Switzerland","http://cimg.sourceforge.net/img/postcard29.jpg")
#@gimp : link = link(0,"[6] Mahvin - Portland/USA","http://cimg.sourceforge.net/img/postcard27.jpg")
#@gimp : link = link(0,"[7] Vincent Roullier - Caen/France","http://cimg.sourceforge.net/img/postcard26.jpg")
#@gimp : link = link(0,"[8] M???? - Munich/Germany","http://cimg.sourceforge.net/img/postcard24.jpg")
#@gimp : link = link(0,"[9] F. Albior - Jaca/Spain","http://cimg.sourceforge.net/img/postcard23.jpg")
#@gimp : link = link(0,"[10] PhotoComIX - Frascati/Italy","http://cimg.sourceforge.net/img/postcard22.jpg")
#@gimp : link = link(0,"[11] Guy Poizat - Cabestany/France","http://cimg.sourceforge.net/img/postcard21.jpg")
#@gimp : link = link(0,"[12] Institut for Biomathematik und Biometrie - Neuherberg/Germany","http://cimg.sourceforge.net/img/postcard20.jpg")
#@gimp : link = link(0,"[13] Jaime - Barcelona/Spain","http://cimg.sourceforge.net/img/postcard14.jpg")
#@gimp : link = link(0,"[14] Jean-Michel Webbe - Guadeloupe/France","http://cimg.sourceforge.net/img/postcard15.jpg")
#@gimp : sep = separator()
#@gimp : note = note{"\nMay the force be with you !"}
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2011/03/30</i>.</small>")
gimp_friends :
  -if @# ratio={w/h} -else ratio=1 -endif
  -rm -_heart80x73 -resize3x -r 150%,150%,1,1,0,0,0.5,0.5
  --*[-1] 70 --*[-2] 110 --*[-3] 255 -*[-4] 255 -a c
  -blur_radial 4 -sharpen 300
  -i[-2] @{"-fitratio_wh "@{-1,w},@{-1,h},$ratio},1,3
  -rand[-2] 0,255 -sh[-2] 1,2 -/[-1] 2 -rm[-1]
  -blur_radial[-2] 10 -sharpen[-2] 600
  -r[-1] [-2],[-2],1,4,0,0,0.5,0.5 -compose_alpha
  135,67,1,1,0 -text[-1] "Greetings to\n  all G'MIC\n  friends !",2,-2,24,1,1
  --dilate[-1] 3 -*[-2] 255 -to_rgb[-2] -j[-3] [-2],{(@{-3,w}-@{-2,w})/2},{(@{-3,h}-@{-2,h})/2.2},0,0,1,[-1]
  -rm[-2,-1]

_heart80x73 :
  40,73,1,1,0 -ellipse 22,22,20,20,0,1,1 -polygon 3,7,37,42,72,42,27,1,1 --mirror x -a x

#@gimp Gmicky / Roddy : gimp_gmicky, gimp_gmicky_preview
#@gimp : Mascot image = choice("Gmicky","Gmicky & Wilber","Roddy")
#@gimp : sep = separator()
#@gimp : note = note{"<b><i>Gmicky</i></b> is the name of the <b>G'MIC</b> mascot. He is a small and cute tiger who knows how to do magic.
#@gimp : <b><i>Gmicky</i></b> is a tiger, i.e. fast, agile and elegant, just as the <b>G'MIC</b> code is :).
#@gimp : As many magicians, <b><i>Gmicky</i></b> knows lot of gimmicks (<b>G'MIC</b>), and he is a direct and friendly competitor of
#@gimp : the ImageMagick's wizard, or the GraphicMagick's frog."}
#@gimp : note = note{"<b><i>Roddy</i></b> is another mascot designed specifically for the <i>Artistic / Rodilius</i> filter of <b>G'MIC</b>."}
#@gimp : note = note{"<b><i>Gmicky</i></b> and <b><i>Roddy</i></b> have been designed by "}
#@gimp : link = link("Mahvelous Mahvin","http://www.mahvin.com/")
#@gimp : sep = separator(), note = note("<small>Authors : <i>David Tschumperl&#233;, Mahvin</i>.      Latest update : <i>2011/05/27</i>.</small>")
gimp_gmicky :
  -rm
  -if {$1==0} -gmicky
  -elif {$1==1} -gmicky_wilber
  -else -roddy
  -endif

gimp_gmicky_preview :
  w={w} h={h} -rm
  -if {$1==0}
    filename=@{-path_tmp}/gmicky_small.cimgz
    url=http://gmic.sourceforge.net/img/gmicky_small.cimgz
  -elif {$1==1}
    filename=@{-path_tmp}/gmicky_wilber_small.cimgz
    url=http://gmic.sourceforge.net/img/gmicky_wilber_small.cimgz
  -else
    filename=@{-path_tmp}/roddy_small.cimgz
    url=http://gmic.sourceforge.net/img/roddy_small.cimgz
  -endif
  -if $filename $filename -else -i $url -o $filename -endif
  -r2dy $h,3 -- 255 -r $w,$h,1,3,0,0,0.5,0.5 -+ 255

#@gimp Tutorials : _none_, _none_
#@gimp : note = note{"\nSome nice people have written tutorials about the use of the <b>G'MIC</b> framework.
#@gimp : They provide useful resources to see what <b>G'MIC</b> is able to do and how you can use it to achieve cool effects.
#@gimp : Feel free to visit the URL below. A big hug goes to them for their efforts !\n"}
#@gimp : sep = separator(), note = note("<b>Features overview</b>")
#@gimp : link = link{0,"1. Official G'MIC discussion group","http://www.flickr.com/groups/gmic/"}
#@gimp : link = link{0,"2. Preview of some G'MIC filters (in French)","http://aljacom.com/~gmic/"}
#@gimp : link = link{0,"3. Preview of some G'MIC filters (in German)","http://www.gimp-atelier.org/forum/viewtopic.php?f=43&t=121"}
#@gimp : link = link{0,"4. G'MIC dein persönlicher Pinsel von Hans (in German)","http://www.gimp-atelier.org/forum/viewtopic.php?p=9972#p9972"}
#@gimp : link = link{0,"5. G'MIC - Nahtloses Muster erstellen von Avarra (in German)","http://www.gimp-atelier.org/forum/viewtopic.php?p=6847#p6847"}
#@gimp : link = link{0,"6. G'MIC - Japanbild von Basteltante-Gudrun (in German)","http://www.gimp-atelier.org/forum/viewtopic.php?f=11&t=16"}
#@gimp : link = link{0,"7. G'MIC - Lueftungsgitter fuer Ventilator von Avarra (in German)","http://www.gimp-atelier.org/forum/viewtopic.php?p=9965#p9965"}
#@gimp : link = link{0,"8. G'MIC - EBV & G'MIC - Objekte dominant gestalten von Avarra (in German)","http://www.gimp-atelier.org/forum/viewtopic.php?p=9903#p9903"}
#@gimp : link = link{0,"9. Schokobecher gefuellt von gimpZora (in German)","http://www.gimp-atelier.org/forum/viewtopic.php?p=9551#p9551"}
#@gimp : sep = separator(), note = note("<b>G'MIC syntax</b>")
#@gimp : link = link{0,"1. Initiation to the G'MIC language","http://zonderr.wordpress.com/2010/09/13/gmic-command-first-steps/"}
#@gimp : link = link{0,"2. Images and formats","http://zonderr.wordpress.com/2010/10/06/gmic-image-and-format/"}
#@gimp : link = link{0,"3. The command line behind the plug-in","http://zonderr.wordpress.com/2010/09/18/gmic-from-the-gimp-plugin-to-the-command-line/"}
#@gimp : link = link{0,"4. Adding a custom filter to the plug-in","http://zonderr.wordpress.com/2010/11/13/howto-create-a-custom-filter-in-the-gmic-plug-in/"}
#@gimp : sep = separator(), note = note("<b>Workflow</b>")
#@gimp : link = link{0,"1. Developping RAW images","http://gmic.sourceforge.net/tutorial.shtml"}
#@gimp : sep = separator(), note = note("<b>Special effects</b>")
#@gimp : link = link{0,"1. How to make caricatures","http://www.mahvin.com/?p=1091"}
#@gimp : link = link{0,"2. Quick Tie-Dye Backgrounds","http://www.mahvin.com/?p=1243"}
#@gimp : link = link{0,"3. How to turn a photo into a realistic handmade sketch","http://www.flickr.com/groups/gmic/discuss/72157624446298923/"}
#@gimp : link = link{0,"4. Playing with the Fourier Transform","http://www.flickr.com/groups/gmic/discuss/72157624462331405"}
#@gimp : sep = separator(), note = note("<b>Video tutorials</b>")
#@gimp : link = link{0,"1. Turn a photo into a graffiti (in german)","http://vimeo.com/7023686"}
#@gimp : link = link{0,"2. Make an old movie from a photo","http://www.youtube.com/watch?v=Qvt5WQWfw9Y"}
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2011/03/30</i>.</small>")

#@gimp Additional filters : gimp_add_filter_sources, _none_
#@gimp : note = note("Select the sets of additional filter you want to add, click on 'Apply', then on 'Refresh' to make them appear in the filter list.")
#@gimp : sep = separator()
#@gimp : note = note("<b><small>Manage sets globally :</small></b>")
#@gimp : Add all filter sets = bool(1)
#@gimp : note = note(), sep = separator()
#@gimp : note = note("<b><small>Manage sets individually :</small></b>")
#@gimp : Add Kairo's filter set = bool(0)
#@gimp : Add Ronounours' filter set = bool(0)
#@gimp : Add Tom Keil's filter set = bool(0)
#@gimp : Add PhotoComiX's filter set = bool(0)
#@gimp : Add Gentlemanbeggar's filter set = bool(0)
#@gimp : Add Naggobot's filter set = bool(0)
#@gimp : Add Iain Fergusson's filter set = bool(0)
#@gimp : Add Garagecoder's filter set = bool(0)
#@gimp : sep = separator()
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2011/03/30</i>.</small>")
gimp_add_filter_sources : -skip ${2=0},${3=0},${4=0},${5=0},${6=0},${7=0},${8=0},${9=0}
  -l[]
    -if {$1||$2} ({'http://mpkaro.helmholtz-muenchen.de/~karo/karos.gmic'},0) -endif
    -if {$1||$3} ({'http://www.greyc.ensicaen.fr/~dtschump/ronounours.gmic'},0) -endif
    -if {$1||$4} ({'http://www.tkfilter.bplaced.net/tomkeil.gmic'},0) -endif
    -if {$1||$5} ({'http://s406833247.websitehome.co.uk/gmic/photocomix.gmic'},0) -endif
    -if {$1||$6} ({'http://gentlemanbeggar.bplaced.net/gentlemanbeggar_gmic.gmic'},0) -endif
    -if {$1||$7} ({'http://www.saunalahti.fi/naggobot/naggobot.gmic'},0) -endif
    -if {$1||$8} ({'http://www.iain.bplaced.net/iain_fergusson.gmic'},0) -endif
    -if {$1||$9} ({'http://s406833247.websitehome.co.uk/gmic/garagecoder.gmic'},0) -endif
    gmic_path=$GMIC_GIMP_PATH
    -if {!narg($gmic_path)} gmic_path=@{-path_user}/ -else gmic_path=$GMIC_GIMP_PATH/ -endif
    -if {!@{-is_windows}} gmic_path=${gmic_path}. -endif
    gmic_path=${gmic_path}gmic_sources.cimgz
    -o $gmic_path
    -rm
  -endl

#@gimp Share faves : gimp_share_faves, _none_
#@gimp : note = note{"Use this filter to <b>share</b> your favorite <b>G'MIC</b> filters with other users of the <b>G'MIC</b> plug-in.
#@gimp : Here, you can :\n\n
#@gimp : * <b>Export</b> the content of your <i>Faves</i> folder, so you share your favorite filters with other people.\n
#@gimp : * <b>Import</b> <i>Faves</i> filters, shared by other people (who used this filter in 'Export' mode).\n\n
#@gimp : To be able to export your <i>Faves</i>, an active Internet connection is required. When importing <i>Faves</i>,
#@gimp : the new filters are appended to your existing <i>Faves</i> list. You need click the 'Refresh filters' button after import to
#@gimp : make imported faves visible. Remember also that you can rename filters in your <i>Faves</i>
#@gimp : by double-clicking on the filter name !\n\n
#@gimp : <i>Thanks for sharing your presets !</i>\n"}
#@gimp : sep = separator()
#@gimp : Mode = choice("Export faves","Import faves")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2012/04/06</i>.</small>")
gimp_share_faves :
  gmic_path=$GMIC_GIMP_PATH
  -if {!narg($gmic_path)} gmic_path=@{-path_user}/ -endif
  -if {!@{-is_windows}} gmic_path=${gmic_path}. -endif
  gmic_path=${gmic_path}gmic_faves
  -l[]

  # Import shared faves
  #---------------------
  -if $1
    -if $gmic_path -i raw:${gmic_path},uchar -endif
    -l[]
      -i "http://www.greyc.ensicaen.fr/~dtschump/gmic/faves.raw",uchar
      -s -,10
      -rm_duplicates
      -if @#
        -r 2,50%,1,1,-1 -hex2img8

        # Remove potentially dangerous filters.
        -replace_seq "103,105,109,112,95,99,117,115,116,111,109,95,99,111,100,101","100,105,115,97,98,108,101,100"
      -endif
    -endl

    # Sort alphabetically.
    i=@# --z 0,1,0,8 -f[$i--1] '50^(h-1-y)*(i-65)' -r[$i--1] 1,1,1,1,2
    -a[$i--1] y --f[-1] 'y' -a[-2,-1] x -sort[-1] +,y -z[-1] 1,1
    -repeat {h} name$>=@{$>,n} -nm[$>] sortlist$> -done
    -repeat {h} -mv[sortlist{i(0,$>)}] -1 -done
    -repeat {h} -nm[$>] ${name{i(0,$>)}} -done
    -rm[-1]

    -i[1--1] (10) -a y
    -o raw:${gmic_path},uchar

  # Export current faves
  #----------------------
  -else
    -if $gmic_path -i raw:${gmic_path},uchar -s -,10 -img82hex -endif
    -repeat @# -u @{$>,t} -l[] -i "http://www.greyc.ensicaen.fr/~dtschump/gmic/poke_faves.cgi?"@{} -rm -onfail -endl -done
  -endif
  -rm -endl

# Clean shared fave files on server.
# (To be used by server's owner only).
clean_shared_faves :
  path="/home/dtschump/dtschump/public_html/gmic/faves.raw"
  -l[] -i raw:$path,uchar
  -s -,10
  -rm_duplicates
  -if @#
    -i[1--1] (10) -a y
    -o raw:$path,uchar
  -endif
  -rm
  -endl

#@gimp Visitors book : gimp_visitors_book, _none_
#@gimp : note = note{"We would be very interested to get your impressions about the <b>G'MIC</b> plug-in.
#@gimp : This would help us to grasp the general users profile, in order to improve our plug-in in the future.
#@gimp : Just fill the entries you want below, and click on buttons <b>Apply</b> or <b>OK</b> to actually
#@gimp : send us these informations (an active Internet connection is required)."}
#@gimp : note = note{"<i>Many thanks for your contribution !</i>"}
#@gimp : sep = separator()
#@gimp : Name/Nickname = _text("")
#@gimp : Gender = choice("Unknown","Male","Female")
#@gimp : Age = _text("")
#@gimp : Profession = _text("")
#@gimp : Hobbies = _text("")
#@gimp : sep = separator()
#@gimp : How often I run G'MIC = choice("Unknown","Never","Rarely","Occasionally","Often","Very often","Every time")
#@gimp : I run G'MIC mainly on = choice("Unknown","Linux","BSD","Windows <= XP","Windows Vista","Windows 7","Mac OS","Other OS")
#@gimp : Favorite G'MIC filter(s) = _text("")
#@gimp : I have G'MIC Faves = choice("Unknown","No","Yes")
#@gimp : I use 'gmic' on the command line = choice("Unknown","No","Yes")
#@gimp : I am a G'MIC contributor = choice("Unknown","No","Yes")
#@gimp : sep = separator()
#@gimp : Additional comments = _text(1,"\n\n\n")
#@gimp : sep = separator(), note = note{"<small><b>Note : </b> This is a purely <i>anonymous</i> process. None of the requested informations
#@gimp : are mandatory, feel free to skip those you are not interested in !</small>"}
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2011/07/01</i>.</small>")
gimp_visitors_book :
  -skip "${1=Anonymous},${2=0},${3=Unknown},${4=Unknown},${5=Unknown}"   # Name/Gender/Age/Profession/Hobbies.
  -skip "${6=0},${7=0},${8=Unknown},${9=0},${10=0},${11=0}"              # G'MIC-specific informations.
  -skip "${12=Unknown}"                                                  # Additional comments.
  -str2hex "$1"{`1`}\
           "$2"{`1`}\
           "$3"{`1`}\
           "$4"{`1`}\
           "$5"{`1`}\
           "$6"{`1`}\
           "$7"{`1`}\
           "$8"{`1`}\
           "$9"{`1`}\
           "$10"{`1`}\
           "$11"{`1`}\
           "$12"
  -l[] -i "http://www.greyc.ensicaen.fr/~dtschump/gmic/poke.cgi?"@{} -rm -onfail -endl

# Display all messages from the visitors book.
# (to be called from the command line version 'gmic').
# '$1' can be { 1=new users only | 2=messages only | 3=both }
visitors_book : -skip ${1=3},${2="http://www.greyc.ensicaen.fr/~dtschump/gmic/messages.raw"}
  -v - -rm
  empty_entry=416e6f6e796d6f7573013001556e6b6e6f776e01556e6b6e6f776e01556e6b6e6f776e0130013001556e6b6e6f776e013001300130010a0a0a
  last_entry=0
  m=1 n=1
  -i raw:$2,char
  -s -,10
  -repeat @#
    -if {{@{0,t}'!='$empty_entry}" && "{@{0,t}'!='$last_entry}}
      last_entry=@{0,t}
      ({'@{-hex2str\ @{0,t}}'}) -l[-1] -s -,1
      -if {$1&1" && "@#==1}
        -v +
        -e[] "-------- < User ""#"$m" : "@{0,t}" > ---------"
        -v - -rm
        m={$m+1}
      -elif {$1&1" && "@#==2}
        -v +
        -e[] "-------- < User ""#"$m" : "@{0,t}/@{1,t}" > ---------"
        -v - -rm
        m={$m+1}
      -elif {$1&2" && "@#>2}
        -if {@#>=11} -autocrop[11] 10 -endif
        -v +
        -e[] "-------- < Entry ""#"$n" > --------"
        -e[] ". Name : "@{0,t}
        -e[] ". Gender : "@{-_visitors_book_gender@{1,t}}
        -e[] ". Age : "@{2,t}
        -e[] ". Profession : "@{3,t}
        -e[] ". Hobbies : "@{4,t}
        -e[] ". How often I run G'MIC : "@{-_visitors_book_frequency@{5,t}}
        -e[] ". I run G'MIC mainly on : "@{-_visitors_book_os@{6,t}}
        -e[] ". Favorite G'MIC filter : "@{7,t}
        -e[] ". I have G'MIC Faves : "@{-_visitors_book_bool@{8,t}}
        -e[] ". I use 'gmic' on the command line : "@{-_visitors_book_bool@{9,t}}
        -e[] ". I am a G'MIC contributor : "@{-_visitors_book_bool@{10,t}}
        -if {@{11,#}!=1} -e[] ". Additional comments : \n"@{11,t} -endif
        -e[] ""
        -v - -rm
        n={$n+1}
      -endif
      -onfail -e[] " ** WARNING : Incomplete data for entry ""#"$>"." -v - -rm
      -endl
    -endif
  -rm[0] -done -rm -v +

_visitors_book_gender0 : -u Unknown
_visitors_book_gender1 : -u Male
_visitors_book_gender2 : -u Female

_visitors_book_frequency0 : -u Unknown
_visitors_book_frequency1 : -u Never
_visitors_book_frequency2 : -u Rarely
_visitors_book_frequency3 : -u Occasionally
_visitors_book_frequency4 : -u Often
_visitors_book_frequency5 : -u Very\ often
_visitors_book_frequency6 : -u Every\ time

_visitors_book_os0 : -u Unknown
_visitors_book_os1 : -u Linux
_visitors_book_os2 : -u BSD
_visitors_book_os3 : -u Windows\ <=\ XP
_visitors_book_os4 : -u Windows\ Vista
_visitors_book_os5 : -u Windows\ 7
_visitors_book_os6 : -u Mac\ OS
_visitors_book_os6 : -u Other\ OS

_visitors_book_bool0 : -u Unknown
_visitors_book_bool1 : -u No
_visitors_book_bool2 : -u Yes


#@gimp _<b>Arrays &amp; frames</b>
#----------------------------------


#@gimp Regular array : gimp_array, gimp_array_preview(1)
#@gimp : X-tiles = int(2,1,10)
#@gimp : Y-tiles = int(2,1,10)
#@gimp : X-offset = float(0,0,100)
#@gimp : Y-offset = float(0,0,100)
#@gimp : Mirror = choice("None","X-axis","Y-axis","XY-axes")
#@gimp : Size = _choice("Shrink", "Expand", "Repeat [Memory consuming !]")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_array :
  -shift -$3%,-$4%,0,0,2
  -if {$5&1} -mirror x -endif -if {$5>1} -mirror y -endif
  -array $1,$2,$6

gimp_array_preview :
  -gimp_array $1,$2,$3,$4,$5,0

#@gimp Faded array : gimp_array_fade, gimp_array_fade_preview(1)
#@gimp : X-tiles = int(2,1,10)
#@gimp : Y-tiles = int(2,1,10)
#@gimp : X-offset = float(0,0,100)
#@gimp : Y-offset = float(0,0,100)
#@gimp : Fade start = float(80,1,100)
#@gimp : Fade end = float(90,1,100)
#@gimp : Mirror = choice("None","X-axis","Y-axis","XY-axes")
#@gimp : Size = _choice("Shrink", "Expand", "Repeat [Memory consuming !]")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_array_fade :
  -if {$7&1} -mirror x -endif -if {$7>1} -mirror y -endif
  -array_fade $1,$2,$5,$6,$8
  -shift -$3%,-$4%,0,0,2

gimp_array_fade_preview :
  -gimp_array_fade $1,$2,$3,$4,$5,$6,$7,0

#@gimp Mirrored array : gimp_array_mirror, gimp_array_mirror_preview(1)
#@gimp : Iterations = int(1,1,10)
#@gimp : X-offset = float(0,0,100)
#@gimp : Y-offset = float(0,0,100)
#@gimp : Array mode = choice(2,"X-axis","Y-axis","XY-axes","2XY-axes")
#@gimp : Initialization = choice("Original","Mirror X","Mirror Y","Rotate 90 deg.","Rotate 180 deg.","Rotate 270 deg.")
#@gimp : Expand size = _bool(false)
#@gimp : Crop = int(0,0,100)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_array_mirror : -skip ${7=0}
  -if {$5==1} -mirror x
  -elif {$5==2} -mirror y
  -elif {$5==3} -rotate 90
  -elif {$5==4} -rotate 180
  -elif {$5==5} -rotate 270
  -endif
  -if $7
    -if {$4==0} -columns 0,{100-$7}%
    -elif {$4==1} -lines 0,{100-$7}%
    -elif {$4==2} -z 0,0,{100-$7}%,{100-$7}%
    -elif {$4==3} -z {$7/2}%,{$7/2}%,{100-$7/2}%,{100-$7/2}%
    -endif
  -endif
  -shift -$2%,-$3%,0,0,2
  -array_mirror $1,$4,$6

gimp_array_mirror_preview :
  -gimp_array_mirror $1,$2,$3,$4,$5,0,$7

#@gimp Random array : array_random, array_random(1)
#@gimp : Source X-tiles = int(5,1,20)
#@gimp : Source Y-tiles = int(5,1,20)
#@gimp : Destination X-tiles = int(7,1,20)
#@gimp : Destination Y-tiles = int(7,1,20)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")

#@gimp Random color array : gimp_array_color, gimp_array_color(1)
#@gimp : X-tiles = int(5,1,20)
#@gimp : Y-tiles = int(5,1,20)
#@gimp : Opacity = float(0.5,0,1)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_array_color :
  -repeat @# -l[-1]
    $1,$2,1,3 -rand[-1] 0,255 -to_colormode[-1] @{-2,s} -r[-1] [-2] -*[-1] $3 -*[-2] {1-$3} -+[-2,-1]
  -endl -mv[-1] 0 -done

#@gimp Tileable rotation : gimp_rotate_tileable, gimp_rotate_tileable(1)
#@gimp : Angle = float(45,0,360)
#@gimp : Maximum size factor = int(8,0,20)
#@gimp : Array mode = choice(0,"None","X-axis","Y-axis","XY-axes","2XY-axes")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2011/05/26</i>.</small>")
gimp_rotate_tileable :
  -if $3 -array_mirror 1,{$3-1},1 -endif
  -rotate_tileable $1,{if($3==0,$2,$2/2)}
  -repeat @#
    -if {@{$>,w}==1" && "@{$>,h}==1} -rm -_gimp_no_preview "  Invalid\nimage size" -return -endif
  -done

#@gimp Tiled rotation : gimp_rotate_tiles, gimp_rotate_tiles(1)
#@gimp : X-tiles = int(5,1,80)
#@gimp : Y-tiles = int(5,1,80)
#@gimp : Angle = float(15,0,360)
#@gimp : Opacity = float(1,0,1)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_rotate_tiles :
  -to_rgba -rotate_tiles $3,$1,$2
  -if {$4<1} -repeat @# -s[-1] c -*[-1] $4 -a[-4--1] c -mv[-1] 0 -done -endif

#@gimp Tiled normalization : gimp_normalize_tiles, gimp_normalize_tiles(1)
#@gimp : X-tiles = int(25,1,80)
#@gimp : Y-tiles = int(25,1,80)
#@gimp : Minimal value = float(0,0,255)
#@gimp : Maximal value = float(255,0,255)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
_gimp_normalize_tiles :
  -repeat @# -l[-1] -split_tiles $1,$2 -n $3,$4 -append_tiles $1,$2 -endl -mv[-1] 0 -done

gimp_normalize_tiles :
  -apply_channels "-_gimp_normalize_tiles ${1-4}",$-1

#@gimp Tiled random shift : gimp_shift_tiles, gimp_shift_tiles(1)
#@gimp : X-tiles = int(10,1,30)
#@gimp : Y-tiles = int(10,1,30)
#@gimp : Amplitude = float(10,0,100)
#@gimp : Opacity = float(1,0,1)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_shift_tiles :
  -to_rgba -shift_tiles $1,$2,$3
  -if {$4<1} -repeat @# -s[-1] c -*[-1] $4 -a[-4--1] c -mv[-1] 0 -done -endif

#@gimp Tiled parameterization : gimp_parameterize_tiles, gimp_parameterize_tiles(1)
#@gimp : X-tiles = int(10,1,30)
#@gimp : Y-tiles = int(10,1,30)
#@gimp : Fitting function = choice("Linear","Quadratic")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_parameterize_tiles :
  -if $3
    -quadratize_tiles $1,$2
  -else
    -linearize_tiles $1,$2
  -endif
  -c 0,255

#@gimp Tiled isolation : gimp_isolate_tiles, gimp_isolate_tiles(0)
#@gimp : X-size = float(10,0,100)
#@gimp : Y-size = float(10,0,100)
#@gimp : X-border = float(5,0,100)
#@gimp : Y-border = float(5,0,100)
#@gimp : Keep tiles square = bool(1)
#@gimp : Keep borders square = bool(1)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2011/04/13</i>.</small>")
gimp_isolate_tiles :
  -repeat @# -l[$>] -to_rgba
    -if $5 sx={round(min(w,h)*max($1,$2)/100)} sy=$sx -else sx={round(w*$1/100)} sy={round(h*$2/100)} -endif
    -if $6 bx={max($3,$4)} by=$bx -else bx=$3 by=$4 -endif
    -s x,-$sx
    -repeat @# -l[$>] -s y,-$sy -r 100%,{100+$by}%,1,100%,0,0,0.5,0.5 -a y -endl -done
    -r {100+$bx}%,100%,1,100%,0,0,0.5,0.5 -a x
  -endl -done

#@gimp Image grid : gimp_imagegrid, gimp_imagegrid(0)
#@gimp : X-size = int(10,2,100)
#@gimp : Y-size = int(10,2,100)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_imagegrid :
  -to_rgba -imagegrid $1,$2

#@gimp Taquin : taquin, taquin(1)
#@gimp : X-tiles = int(7,1,20)
#@gimp : Y-tiles = int(7,1,20)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")

#@gimp Random pattern : gimp_array_pattern, gimp_array_pattern_preview(1)
#@gimp : X-tiles = int(10,1,30)
#@gimp : Y-tiles = int(10,1,30)
#@gimp : Density = float(80,0,100)
#@gimp : Angle = float(180,0,180)
#@gimp : Zoom = float(30,0,100)
#@gimp : Opacity = float(1,0,1)
#@gimp : Image size = _choice("Shrink", "Expand", "Repeat [Memory consuming !]")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_array_pattern :
  -to_rgba -array_pattern $1,$2,$3,$4,$5,$6,0

gimp_array_pattern_preview :
  -to_rgba -array_pattern $1,$2,$3,$4,$5,$6,$7

#@gimp Regular frame : gimp_frame, gimp_frame(1)
#@gimp : note = note("<b>Crop parameters :</b>")
#@gimp : X-start = int(0,0,100)
#@gimp : X-end = int(100,0,100)
#@gimp : Y-start = int(0,0,100)
#@gimp : Y-end = int(100,0,100)
#@gimp : sep = separator(), note = note("<b>Frame parameters :</b>")
#@gimp : Width = int(10,0,100)
#@gimp : Height = int(10,0,100)
#@gimp : Color = color(0,0,0,255)
#@gimp : Outline size = int(1,0,100)
#@gimp : Outline color = color(255,255,255,255)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_frame :
 -to_rgba -repeat @#
   -z[-1] $1%,$3%,$2%,$4%
   -frame[-1] $11,$11,${12-15}
   -frame[-1] $5%,$6%,${7-10}
 -mv[-1] 0 -done

#@gimp Cube frame : frame_cube, frame_cube(1)
#@gimp : Depth = float(1,0,100)
#@gimp : X-center = float(0,-2,2)
#@gimp : Y-center = float(0,-2,2)
#@gimp : Left side orientation = choice("Normal","Mirror-X","Mirror-Y","Mirror-XY")
#@gimp : Right side orientation = choice("Normal","Mirror-X","Mirror-Y","Mirror-XY")
#@gimp : Upper side orientation = choice("Normal","Mirror-X","Mirror-Y","Mirror-XY")
#@gimp : Lower sider orientation = choice("Normal","Mirror-X","Mirror-Y","Mirror-XY")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;, Angelo Lama</i>.      Latest update : <i>2012/01/29</i>.</small>")

#@gimp Pattern frame : gimp_frame_pattern, gimp_frame_pattern_preview(1)
#@gimp : Tiles = int(10,3,30)
#@gimp : Pattern = choice(1,"Top layer","Self image")
#@gimp : Iterations = int(1,1,10)
#@gimp : Constrain image size = _bool(1)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_frame_pattern :
  -repeat $3 -frame_pattern $1,$2,$4 -done

gimp_frame_pattern_preview :
  -gimp_frame_pattern $1,$2,$3,1

#@gimp Fuzzy frame : gimp_frame_fuzzy, gimp_frame_fuzzy(0)
#@gimp : Width = int(10,0,99)
#@gimp : Height = int(10,0,99)
#@gimp : Fuzzyness = float(10,0,40)
#@gimp : Smoothness = float(1,0,5)
#@gimp : Color = color(255,255,255,255)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_frame_fuzzy :
  -repeat @#
    ({w*$1/200},{h*$2/200}) -round[-1] 1
    -frame_fuzzy[-2] @-1,$3,$4,$5,$6,$7,$8 -rm[-1]
  -mv[-1] 0 -done

#@gimp Round frame : gimp_frame_round, gimp_frame_round(1)
#@gimp : Sharpness = float(6,0.1,40)
#@gimp : Size = float(20,0,100)
#@gimp : Smoothness = float(0.1,0,15)
#@gimp : Shade = float(0,0,1)
#@gimp : Color = color(255,255,255,255)
#@gimp : Blur frame = float(0,0,100)
#@gimp : Blur shade = float(0.1,0,1)
#@gimp : Blur amplitude = float(3,0,10)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_frame_round :
  -frame_round ${1-8}
  -if $9 -frame_blur $1,{min(99,$1+$9)},$3,$10,$11% -endif

#@gimp Tunnel : gimp_tunnel,gimp_tunnel(1)
#@gimp : Depth = int(4,1,100)
#@gimp : Factor = float(80,1,99)
#@gimp : X-center = float(0.5,0,1)
#@gimp : Y-center = float(0.5,0,1)
#@gimp : Opacity = float(0.2,0,1)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_tunnel :
  -tunnel $1,$2%,$3,$4,$5


#@gimp _<b>Artistic</b>
#-----------------------

#@gimp Cartoon : cartoon, gimp_cartoon_preview(0)
#@gimp : Smoothness = float(2,0,10)
#@gimp : Sharpening = float(200,0,400)
#@gimp : Edge threshold = float(10,1,30)
#@gimp : Edge thickness = float(0.25,0,1)
#@gimp : Color strength = float(1.5,0,3)
#@gimp : Color quantization = int(32,2,256)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_cartoon_preview :
  -gimp_split_preview "-cartoon ${1--2}",$-1

#@gimp Circlism : gimp_circlism, gimp_no_preview
#@gimp : Min radius = int(2,1,100)
#@gimp : Max radius = int(10,1,100)
#@gimp : Smoothness = float(1,0,10)
#@gimp : Edge linearity = float(0.4,0.01,5)
#@gimp : Location linearity = float(3,0.01,5)
#@gimp : Shape = choice(2,"Diamonds","Squares","Circles")
#@gimp : Transparency = bool(0)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2011/10/16</i>.</small>")
gimp_circlism :
  -to_rgb -circlism ${1-6}
  -if $7 -to_rgba -replace_color 0,0,0,0,0,255,0,0,0,0 -endif

#@gimp Cubism : cubism, cubism(1)
#@gimp : Iterations = int(300,1,2000)
#@gimp : Bloc size = float(10,0,40)
#@gimp : Angle = float(90,0,360)
#@gimp : Opacity = float(0.7,0.01,1)
#@gimp : Smoothness = float(0,0,5)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")

#@gimp Ellipsionism : gimp_ellipsionism, gimp_ellipsionism_preview(0)
#@gimp : Primary radius = float(20,1,100)
#@gimp : Secondary radius = float(10,1,100)
#@gimp : Smoothness = float(0.5,0,10)
#@gimp : Opacity = float(0.7,0,1)
#@gimp : Outline = float(8,1,3)
#@gimp : Density = float(0.5,0.1,2)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_ellipsionism :
  -ellipsionism ${^0}

gimp_ellipsionism_preview :
  -gimp_split_preview "-gimp_ellipsionism ${1--2}",$-1

#@gimp Graphic boost : gimp_graphic_boost, gimp_graphic_boost_preview(0)
#@gimp : sep = separator ()
#@gimp : note = note("Unsharp Mask controls")
#@gimp : Radius = float(1.25,0,20)
#@gimp : Darken = float(2,0,10)
#@gimp : sep = separator()
#@gimp : Skip Others Steps = bool(false)
#@gimp : note = note("Check for visual control, UNcheck to reactivate the other controls")
#@gimp : sep = separator()
#@gimp : sep = separator()
#@gimp : note = note("BW_Pencil Controls")
#@gimp : Pencil Size = float(0.15,0,4)
#@gimp : Pencil Amplitude = float(14,0,200)
#@gimp : sep = separator()
#@gimp : Skip Others Steps = bool(false)
#@gimp : sep = separator ()
#@gimp : sep = separator ()
#@gimp : Activate "Pencil Smoother" = bool(true)
#@gimp : note = note(" If unchecked the 3 sliders below are disabled ")
#@gimp : Pencil Smoother Sharpness = float(0.5,0,2)
#@gimp : Pencil Smoother Edge Protection = float(0.45,0,1)
#@gimp : Pencil Smoother Smoothness = float (2,0,10)
#@gimp : sep = separator()
#@gimp : Skip Others Steps = bool(false)
#@gimp : sep = separator ()
#@gimp : sep = separator ()
#@gimp : note = note("Merging Options")
#@gimp : SWAP layers = bool (True)
#@gimp : note = note (""Swap" change the effect of Merging and Intesity")
#@gimp : Merging Option = choice( "Hard Light","Grain Merge","Multiply","Color Burn","Overlay" ,"Value","Darken" ,"Stamp" )
#@gimp : Intensity = float(1,0,1)
#@gimp : sep = separator ()
#@gimp : Add Painter's Touch = bool(true)
#@gimp : note = note("If unchecked the 3 sliders below are disabled")
#@gimp : sep = separator ()
#@gimp : Painter's Touch Sharpness = float(0.5,0,2)
#@gimp : Painter's Edge Protection Flow = float(0.45,0,1)
#@gimp : Painter's Smoothness =float(1,0,10)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>PhotoComiX</i>.      Latest update : <i>2011/01/10 </i>.</small>")
#@gimp : note = link("Filter explained here","http://www.gimpchat.com/viewtopic.php?f=9&t=775")
gimp_graphic_boost :
  -repeat @# -l[$>] -split_opacity -l[0]
    -gimp_unsharp 1,$1,30,3,0,$2,0.40,1,0,0,0
    -if {$3==1} -break -endif
    --gimp_pencilbw $4,$5,0,0,0
    -if {$6==1} -keep[-1] -break -endif
    -if {$7==1} -gimp_anisotropic_smoothing[1] 60,$8,$9,$10,1.1,0.8,30,2,0,1,1,0,1,0 -endif
    -if {$11==1} -keep[-1] -break -endif
    -if {$12==1}  -reverse -endif
  #( Hard Light,Grain Merge, Multiply,Color Burn ,Overlay ,Value, Darken ,Stamp )
    -if {$13==0} -gimp_compose_hardlight $14
    -elif {$13==1} -gimp_compose_grainmerge $14
    -elif {$13==2} -gimp_compose_multiply $14
    -elif {$13==3} -gimp_compose_colorburn $14
    -elif {$13==4} -gimp_compose_overlay $14
    -elif {$13==5} -gimp_compose_value $14,0
    -elif {$13==6} -gimp_compose_darken $14
    -elif {$13==7} -gimp_compose_stamp $14 -endif
    -if {$15==1} -gimp_anisotropic_smoothing 60,$16,$17,$18,1.1,0.8,30,2,0,1,1,0,1,0 -endif
  -endl -a c -endl -done

gimp_graphic_boost_preview :
  -gimp_split_preview "-gimp_graphic_boost ${1--2}",$-1

#@gimp Graphic novel : gimp_novelfx, gimp_novelfx_preview(0)
#@gimp : sep = separator ()
#@gimp : note = note("Apply Local Normalization")
#@gimp : SKIP this step = bool(false)
#@gimp : sep = separator ()
#@gimp : note = note(" Local Normalization Controls")
#@gimp : LN Amplititude = float(2,0,60)
#@gimp : LN Size = float(6,0,64)
#@gimp : LN Neightborhood-Smoothness = float(5,0,40)
#@gimp : LN Average-Smoothness = float(20,0,40)
#@gimp : sep = separator()
#@gimp : SKIP all other steps = bool(false)
#@gimp : sep = separator()
#@gimp : sep = separator()
#@gimp : note = note(" Pencil Options")
#@gimp : Pencil Size = float(0.62,0,4)
#@gimp : Pencil Amplitude = float(14,0,200)
#@gimp : sep = separator()
#@gimp : SKIP all other steps = bool(false)
#@gimp : sep = separator()
#@gimp : sep = separator()
#@gimp : Activate "Pencil Smoother" = bool(true)
#@gimp : note = note(" If unchecked the 3 sliders below are disabled ")
#@gimp : sep = separator()
#@gimp : Pencil Smoother Sharpness = float(0.5,0,2)
#@gimp : Pencil Smoother Edge Protection = float(0.78,0,1)
#@gimp : Pencil Smoother Smoothness = float(1.92,0,10)
#@gimp : sep = separator()
#@gimp : SKIP all other steps = bool(false)
#@gimp : sep = separator ()
#@gimp : sep = separator()
#@gimp : note = note ("Boost Merging Options")
#@gimp : Swap Layers = bool (false)
#@gimp : BOOST Merging Option = choice("Overlay","Multiply","Soft light","Color Burn","Darken","Stamp","Hard Light","Value","Grain Merge","Freeze")
#@gimp : Opacity = float(1,0,1)
#@gimp : sep = separator ()
#@gimp : Add Painter's Touch = bool(true)
#@gimp : sep = separator ()
#@gimp : Painter's Touch Sharpness = float(0.5,0,2)
#@gimp : Painter's Edge Protection Flow = float(0.8,0,1)
#@gimp : Painter's Smoothness =float(1.28,0,10)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>PhotoComiX</i>.      Latest update : <i>2011/04/24</i>.</small>")
#@gimp : note = link("Filter explained here","http://www.gimpchat.com/viewtopic.php?f=9&t=1582")
gimp_novelfx :
  -repeat @# -l[$>] -split_opacity -l[0]
    -if {$1==0} -gimp_normalize_local $2,$3,$4,$5,1,3,0 -elif {$1==1} -gimp_do_nothing -endif
    -if {$6==0} --gimp_pencilbw $7,$8,0,0,0 -endif
	-if {$9==1} -keep[-1] -break -endif
      -if {$10==1} -gimp_anisotropic_smoothing[-1] 60,$11,$12,$13,1.1,0.8,30,2,0,1,1,0,1,0 -endif
	  -if {$14==1} -keep[-1] -break -endif
	  -if {$15==1} -reverse -endif
	  #choice ("Overlay","Multiply","Soft light","Color Burn,Darken,Stamp,Hard #Light,Value,Grain Merge,Freeze )
      -if {$16==0} -gimp_compose_overlay[-1,0] $17
      -elif {$16==1} -gimp_compose_multiply[-1,0] $17
      -elif {$16==2} -gimp_compose_softlight[-1,0] $17
      -elif {$16==3} -gimp_compose_colorburn[-1,0] $17
      -elif {$16==4} -gimp_compose_darken[-1,0] $17
      -elif {$16==5} -gimp_compose_stamp[-1,0] $17
      -elif {$16==6} -gimp_compose_hardlight[-1,0] $17
      -elif {$16==7} -reverse[1,0] -gimp_compose_value[-1,0] $17,0
      -elif {$16==8} -gimp_compose_grainmerge[-1,0] $17
	  -elif {$16==8} -gimp_compose_freeze[-1,0] $17 -endif
      -if {$18==1} -gimp_anisotropic_smoothing 60,$19,$20,$21,1.1,0.8,30,2,0,1,1,0,1,0 -endif
  -endl -a c -endl -done

gimp_novelfx_preview :
  -gimp_split_preview "-gimp_novelfx ${1--2}",$-1

#@gimp Kaleidoscope : gimp_kaleidoscope, gimp_kaleidoscope(1)
#@gimp : X-center = float(0.5,0,1)
#@gimp : Y-center = float(0.5,0,1)
#@gimp : X-offset = float(0,0,100)
#@gimp : Y-offset = float(0,0,100)
#@gimp : Radius cut = float(100,0,100)
#@gimp : Angle cut = float(10,0,100)
#@gimp : Borders = choice(2,"Black","Nearest","Repeat")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_kaleidoscope :
  -shift $3%,$4%,0,0,2 -kaleidoscope $1,$2,$5,$6,$7

#@gimp Kuwahara : gimp_kuwahara, gimp_kuwahara_preview(0)
#@gimp : Iterations = int(2,1,20)
#@gimp : Radius = int(5,1,30)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2011/05/31</i>.</small>")
gimp_kuwahara :
  -apply_channels "-repeat $1 -kuwahara $2 -done",$3,0

gimp_kuwahara_preview :
  -gimp_split_preview "-gimp_kuwahara ${1--2}",$-1

#@gimp Lylejk's painting : gimp_lylejk_painting, gimp_lylejk_painting_preview(0)
#@gimp : Iterations = int(2,1,20)
#@gimp : Radius = int(4,1,30)
#@gimp : Canvas = float(10,0,100)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Authors : <i>Lyle Kroll, David Tschumperl&#233;</i>.      Latest update : <i>2011/09/21</i>.</small>")
#@gimp : note = link("Filter Explained here","http://www.gimpchat.com/viewtopic.php?f=10&t=2624")
gimp_lylejk_painting :
  -repeat @#
    --gimp_lylejk_stencil[-1] 10,10.49,0.75,0
    -smooth[-1] 300,0.26,1,0,7 -sharpen[-1] $3
    [-1] -rv[-3--1]
    -gimp_compose_lighten[-2,-1] 0.5
    -gimp_compose_grainmerge[-2,-1] 1
    -gimp_kuwahara[-1] $1,$2,0
    -texturize_canvas[-1] $3,4
  -mv[-1] 0 -done

gimp_lylejk_painting_preview :
  -gimp_split_preview "-gimp_lylejk_painting ${1--2}",$-1

#@gimp Morphology painting : gimp_morphopaint, gimp_morphopaint_preview(0)
#@gimp : sep = separator()
#@gimp : note = note("Creates a painting using Morphology-, Segmentation- and Painting- filters. CPU intensive filter that may take long.")
#@gimp : sep = separator()
#@gimp : note = note("Morphology settings")
#@gimp : sep = separator()
#@gimp : Method = choice(1,"Erosion","Dilation","Opening","Closing")
#@gimp : MorphoStrenght = int(18,2,60)
#@gimp : Shape = choice(2,"Square","Octagonal","Circular")
#@gimp : sep = separator()
#@gimp : note = note("Lightness for Morpholayer")
#@gimp : Black Point = int(25,0,50)
#@gimp : Expand Shadows = int(100,50,255)
#@gimp : Compress Highlights = int(230,200,255)
#@gimp : sep = separator()
#@gimp : note = note("Smoothing strength")
#@gimp : Spread amount = int(8,0,20)
#@gimp : Blurr Strength = int(3,0,10)
#@gimp : sep = separator()
#@gimp : note = note("Segmentation settings")
#@gimp : Edge threshold = float(4,0,15)
#@gimp : Smoothness = float(0.5,0,5)
#@gimp : sep = separator()
#@gimp : note = note("Painting Settings")
#@gimp : Abstraction = int(2,1,10)
#@gimp : Details scale = float(0.5,0,5)
#@gimp : Smoothness = float(200,0,1000)
#@gimp : sep = separator()
#@gimp : Merge layers? = bool(1)
#@gimp : note = note("When unchecked the filter will output layers separately for manual composing. Set G'Mic output to new layers.")
#@gimp : Paintstroke = float(1,0,1)
#@gimp : Segments = float(1,0,1)
#@gimp : Morphology = float(1,0,1)
#@gimp : Normalize = bool(1)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>Arto Huotari</i>.      Latest update : <i>2011/09/03</i>.</small>")
#@gimp : note = link("Filter Explained here","http://www.flickr.com/photos/naggobot/6108637935/")
gimp_morphopaint :
  --gimp_morpho[0] $1,$2,0,2,0,$3,0 #Morpho as nro 1
  --gimp_apply_curve[1] $4,50,$5,200,$6,-1,128,-1,128,-1,128,255,1,3,0,0,0 #Curved morpho as nro 2
  -gimp_spread[1] $7,$7,0,0 #Spread Morpho nro 1
  -gimp_gaussian_blur[2] $8,0,0,1,0,0,0 #Blurr Morpho+Spread nro 1
  -gimp_segment_watershed[1] $9,$10,0,0 #Segment Morpho+Spread+Blurr nro 1
  --gimp_painting[0] $11,$12,1.5,$13,1,0 #Paint from original nro 0
  -remove[0] #Remove original from stack
  -reverse[0,2] #reverse images to logical order (Important if output to Gimp)
  -reverse[1,2]
  -if $14
  -mul[2] {$17/3} #Morphology
  -mul[0] {$15/3} #Paint stroke
  -mul[1] {$16/3} #Segments
  -add[1] [2] #Combine images
  -add[1] [0]
  -if $18 -normalize[1] 0,255 -endif #Conditional normalize to get the image to correct range
  -remove[0,2] #remove extra images
-endif

gimp_morphopaint_preview :
  -gimp_split_preview "-gimp_morphopaint ${1--2}",$-1

#@gimp Old photograph : old_photo, old_photo(1)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")

#@gimp Painting : gimp_painting, gimp_painting_preview(0)
#@gimp : Abstraction = int(5,1,10)
#@gimp : Details scale = float(2.5,0,5)
#@gimp : Color = float(1.5,0,4)
#@gimp : Smoothness = float(50,0,1000)
#@gimp : Sharpen shades = bool(1)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Authors : <i>Lyle Kroll, Angelo Lama, David Tschumperl&#233;</i>.\nLatest update : <i>2011/02/28</i>.</small>")
gimp_painting : -skip ${4=0},${5=0}
  -repeat @# -l[$>]
    -to_colormode {max(3,s)} -split_opacity -rv
    -repeat $1 -gimp_normalize_local[-1] 10,6,5,20,1,3 -done
    -gimp_anisotropic_smoothing[-1] {100*$2},0.2,1,$2,{2*$2},0.8,90,2,0,1,1,2,1
    -gimp_mix_lab[-1] 1,0,0,$3,0,0.5,$3,0,0.5,0,2,0
    -if $5 -gimp_segment_watershed[-1] 10,1,0 -endif
    -smooth[-1] $4,0,1,1,1
    -rv -a c
  -endl -done

gimp_painting_preview :
  -gimp_split_preview "-gimp_painting ${1--2}",$-1

#@gimp Pen drawing : gimp_pen_drawing, gimp_pen_drawing_preview(0)
#@gimp : Amplitude = float(10,0,30)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_pen_drawing :
  -to_rgb -drawing $1

gimp_pen_drawing_preview :
  -gimp_split_preview "-gimp_pen_drawing ${1--2}",$-1

#@gimp Polaroid : gimp_polaroid, gimp_polaroid(1)
#@gimp : Frame size = int(10,0,400)
#@gimp : Bottom size = int(20,0,400)
#@gimp : X-shadow = float(0,-20,20)
#@gimp : Y-shadow = float(0,-20,20)
#@gimp : Smoothness = float(3,0,5)
#@gimp : Angle = float(20,-180,180)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_polaroid :
  -polaroid $1,$2 -drop_shadow $3%,$4%,$5% -rotate $6,0

#@gimp Random color ellipses : gimp_color_ellipses, gimp_color_ellipses(1)
#@gimp : Density = int(400,0,3000)
#@gimp : Radius = float(8,0,30)
#@gimp : Opacity = float(0.1,0.01,0.5)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_color_ellipses :
  -to_rgb -color_ellipses $1,$2,$3

#@gimp Reflection : gimp_reflect, gimp_reflect(1)
#@gimp : Height = float(50,0,100)
#@gimp : Attenuation = float(1,0.1,4)
#@gimp : Color = color(110,160,190,64)
#@gimp : Waves amplitude = float(0,0,100)
#@gimp : Waves smoothness = float(1.5,0,4)
#@gimp : X-angle = float(0,-10,10)
#@gimp : Y-angle = float(-3.30,-10,10)
#@gimp : Focale = float(7,0,10)
#@gimp : Zoom = float(1.5,1,5)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_reflect :
  -repeat @#
    -to_rgba[-1] --lines[-1] {100-$1}%,100% -mirror[-1] y -water[-1] $7,$8
    -s[-1] c
    -f[-4] "(i*(255-$6) + $6*$3)/255"
    -f[-3] "(i*(255-$6) + $6*$4)/255"
    -f[-2] "(i*(255-$6) + $6*$5)/255" -a[-4--1] c
    -*[-1] '(h^$2-y^$2)/h^$2' -a[-2,-1] y
    100%,100%,100%,1,$11*$12*(x/w-0.5)
    100%,100%,100%,1,$11*$12*(y/h-0.5)
    100%,100%,100%,1,"$10*(x/w-0.5) + $9*(y/h-0.5) + $11"
    -/[-3] [-1] -+[-3] 0.5 -*[-3] @{-3,w}
    -/[-2,-1] -+[-1] 0.5 -*[-1] {h}
    -a[-2,-1] c -warp[-2] [-1],0,1,0 -rm[-1]
  -mv[-1] 0 -done
  -autocrop 0,0,0,0

#@gimp Rodilius : gimp_rodilius, gimp_rodilius_preview(1)
#@gimp : Amplitude = float(10,0,30)
#@gimp : Thickness = float(10,0,100)
#@gimp : Sharpness = float(300,0,1000)
#@gimp : Orientations = int(5,2,36)
#@gimp : Offset = float(30,0,180)
#@gimp : Color mode = choice(1,"Darker","Lighter")
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Authors : <i>Rod/GimpChat, David Tschumperl&#233;</i>.      Latest update : <i>2011/09/28</i>.</small>")
gimp_rodilius :
  -apply_channels "-rodilius ${1-6}",$7,0

gimp_rodilius_preview :
  -gimp_split_preview "-rodilius ${1--2}",$-1

#@gimp Rotoidoscope : gimp_rotoidoscope, gimp_rotoidoscope(1)
#@gimp : X-center = float(0.5,0,1)
#@gimp : Y-center = float(0.5,0,1)
#@gimp : Angular tiles = int(10,1,72)
#@gimp : Smoothness = float(0.5,0,5)
#@gimp : Borders = choice(2,"Black","Nearest","Repeat")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_rotoidoscope :
  -rotoidoscope {$1*100}%,{$2*100}%,$3,$4%,$5

#@gimp Soft glow : gimp_glow, gimp_glow_preview(0)
#@gimp : Amplitude = float(6,0,20)
#@gimp : note = note()
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_glow :
  -apply_channels "-glow $1",$2,0

gimp_glow_preview :
  -gimp_split_preview "-gimp_glow ${1--2}",$-1

#@gimp Tetris effect : gimp_tetris, gimp_tetris(0)
#@gimp : Scale = int(10,1,20)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_tetris :
  -to_rgb -tetris $1

#@gimp Watercolor : gimp_watercolor, gimp_watercolor_preview(1)
#@gimp : sep = separator(), note = note("General settings:")
#@gimp : Color intensity = float(1.8,0,4)
#@gimp : Light colors = float(0.1,0,1)
#@gimp : Dark colors = float(1,0,10)
#@gimp : sep = separator(), note = note("Line art settings:")
#@gimp : Line art details = float (80,50,100)
#@gimp : Line art smoothness = float(0,0,10)
#@gimp : Line art strength = float(0.5,0,1)
#@gimp : Line art style = choice("pencil","ink","comic style")
#@gimp : Line art fade = float(0,0,100)
#@gimp : sep = separator(), note = note("Color brushes settings:")
#@gimp : Brush style = choice("modern","classic","abstract","line","smooth")
#@gimp : Cyan brush size = float(2,0,50)
#@gimp : Cyan stroke strength = float(0,-5,5)
#@gimp : Cyan edge distance = float(2,0,10)
#@gimp : Cyan abstraction = float(4,0,10)
#@gimp : Magenta brush size = float(2,0,50)
#@gimp : Magenta stroke strength = float(0,-5,5)
#@gimp : Magenta edge distance = float(3,0,10)
#@gimp : Magenta abstraction = float(3,0,10)
#@gimp : Yellow brush size = float(2,0,50)
#@gimp : Yellow stroke strength = float(0,-5,5)
#@gimp : Yellow edge distance = float(4,0,10)
#@gimp : Yellow abstraction = float(2,0,10)
#@gimp : sep = separator(), note = note("Paper and ambience settings:")
#@gimp : Paper color black = bool(0)
#@gimp : Add paper texture = bool(0)
#@gimp : Invert colors = bool(0)
#@gimp : Ambient light = float(0,-50,50)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Authors : <i>Tom Keil and Arto Huotari </i>  Latest update : <i>2011/02/19</i>.</small>")
#@gimp : note = link("Tutorial download","http://www.slideshare.net/ArtoHuotari/gmig-water-color-filter-tutorial")
#@gimp : note = link("Video demonstration here","http://vimeo.com/19713850")
gimp_watercolor :
  -repeat @# -l[$>]
  #secure details:
  -if {$7==0} --gimp_gradient_norm $5,0.5,{99.99-$4},$4,1,0
  -elif {$7==1} --gimp_edges {$5/3.5},{95-$4},0,0
  -elif {$7==2} --gimp_edges {$5/3.5},{95-$4},0,0
  --gimp_mix_hsv[0] 1,0,0,1,-1,0,1,0,0,0,2,0
  -gimp_channel_processing[2] 1,1,0,{$5/10},4,{{$4-50}*2},100,256,0,0,0,2,7,0
  -reverse[1,2] -gimp_compose_multiply[1,2] {0.5+{$6/2}}
  -endif -gimp_frame_round[1] 5,$8,15,0,255,255,255,255,0,0.1,3

  #image preparation:
  -gimp_anisotropic_smoothing[0]
  60,0.16,{{20/50}+0.6},{{20/9}+0.6},2.35,0.8,30,2,0,1,1,0,1
  --gimp_do_nothing[0] --negative[0] -move[1] 4
  -gimp_gaussian_blur[2] {{w+h}/100},0,0,1,0,0,0
  -gimp_compose_dodge[1,2] 1
  -gimp_mix_lab[0] 1,0,0,$1,0,0,$1,0,0,0,2,0
  -reverse[0,1]
  -gimp_compose_colorburn[0,1] $2

  --luminance[0] -reverse[1,2]
  -gimp_channel_processing[1] 1,1,0,0,4,{$3*5},100,256,0,0,0,2,0,0
  -gimp_gaussian_blur[1] $3,0,0,1,0,0,0
  -gimp_channel_processing[1] 1,1,0,0,4,0,99,256,0,1,0,2,0,0
  -gimp_replace_color[1] 1,0,255,255,255,255,0,0,0,0
  -gimp_spread[1] {$3*2},{$3*2},0,0
  -gimp_gaussian_blur[1] {{w+h}/1000},0,0,1,0,0,0
  -reverse[0,1] -gimp_compose_multiply[0,1] 1

  #channel and mask creation:
  -split[0] c
  -if {$9==0} --negative[0] --negative[1] --negative[2]
  -elif {$9==1} --fill_color[0] 255,255,255 --fill_color[0] 255,255,255
  --fill_color[0] 255,255,255
  -elif {$9==2} --fill_color[0] 255,255,255 --fill_color[0] 255,255,255
  --fill_color[0] 255,255,255
  -elif {$9==3} --gimp_edges[0] {$10/5},{$13*5},1,0
  --gimp_edges[1] {$14/5},{$17*5},1,0 --gimp_edges[2] {$18/5},{$21*5},1,0
  -elif {$9==4} --negative[0] --negative[1] --negative[2] -endif

  #channel and mask processing:
  -gimp_channel_processing[0] 1,{{$11/5}+1},{$11/50},0,0,0,100,256,0,0,0,2,0,0
  -if {$9!=2}
  -gimp_gaussian_blur[0] $10,0,0,1,0,0,0
  -else -cubism[0] 300,{$13*5},{$13*36},1,{$10/50} -endif
  -if {$9==0}
  -gimp_channel_processing[-3] 1,{{$11/5}+1},{$11/50},0,0,0,100,256,0,0,0,2,0,0
  -cubism[-3] 300,{$13*5},{$13*36},1,{$10/50} -endif
  -if {$9==4}
  -gimp_channel_processing[-3] 1,{{$11/5}+1},{$11/50},0,0,0,100,256,0,0,0,2,0,0
  -gimp_painting[-3] $13,1.5,2 -endif
  -gimp_frame_fuzzy[-3] {$12*5},{$12*5},{$13*20},{$10/2},0,0,0,255

  -gimp_channel_processing[1] 1,{{$15/5}+1},{$15/50},0,0,0,100,256,0,0,0,2,0,0
  -if {$9!=2}
  -gimp_gaussian_blur[1] $14,0,0,1,0,0,0
  -else -cubism[1] 300,{$17*5},{$17*36},1,{$14/50} -endif
  -if {$9==0}
  -gimp_channel_processing[-2] 1,{{$15/5}+1},{$15/50},0,0,0,100,256,0,0,0,2,0,0
  -cubism[-2] 300,{$17*5},{$17*36},1,{$14/50} -endif
  -if {$9==4}
  -gimp_channel_processing[-2] 1,{{$15/5}+1},{$15/50},0,0,0,100,256,0,0,0,2,0,0
  -gimp_painting[-2] $17,1.5,2 -endif
  -gimp_frame_fuzzy[-2] {$16*5},{$16*5},{$17*20},{$14/2},0,0,0,255

  -gimp_channel_processing[2] 1,{{$19/5}+1},{$19/50},0,0,0,100,256,0,0,0,2,0,0
  -if {$9!=2}
  -gimp_gaussian_blur[2] $18,0,0,1,0,0,0
  -else -cubism[2] 300,{$21*5},{$21*36},1,{$18/50} -endif
  -if {$9==0}
  -gimp_channel_processing[-1] 1,{{$19/5}+1},{$19/50},0,0,0,100,256,0,0,0,2,0,0
  -cubism[-1] 300,{$21*5},{$21*36},1,{$18/50} -endif
  -if {$9==4}
  -gimp_channel_processing[-1] 1,{{$19/5}+1},{$19/50},0,0,0,100,256,0,0,0,2,0,0
  -gimp_painting[-1] $21,1.5,2  -endif
  -gimp_frame_fuzzy[-1] {$20*5},{$20*5},{$21*20},{$18/2},0,0,0,255
  -to_gray[-1] -to_gray[-2] -to_gray[-3] -to_rgba[0] -to_rgba[1] -to_rgba[2]

  #recombine image:
  -split[0] c -reverse[3,-3] -compose_multiply[3,-3] -append[0,1,2,3] c
  -split[1] c -reverse[4,-2] -compose_multiply[4,-2] -append[1,2,3,4] c
  -split[2] c -reverse[5,-1] -compose_multiply[5,-1] -append[2,3,4,5] c
  -if {$22==0} --fill_color[0] 255,255,255 -else --fill_color[0] 0 -endif
  -reverse[0,-1]  -compose_rgba[0,-1]
  -if {$22==0} --fill_color[1] 255,255,255 -else --fill_color[1] 0 -endif
  -reverse[1,-1] -compose_rgba[1,-1]
  -if {$22==0} --fill_color[2] 255,255,255 -else --fill_color[2] 0 -endif
  -reverse[2,-1] -compose_rgba[2,-1]
  -to_gray[0] -to_gray[1] -to_gray[2] -append[0,1,2] c
  -if {$23==1} -gimp_paper 0,0 -endif
  -if {$24==1} -negative[0] -endif
  -gimp_mix_lab 1,$25,0,1,0,0,1,0,0,0,2,0
  -reverse[0,1] -gimp_compose_multiply[0,1] $6
  -endl -done

gimp_watercolor_preview :
  -gimp_split_preview "-gimp_watercolor ${1--2}",$-1

#@gimp Warhol : warhol, warhol(1)
#@gimp : X-tiles = int(3,1,10)
#@gimp : Y-tiles = int(3,1,10)
#@gimp : Smoothness = float(2,0,10)
#@gimp : Color = float(40,0,60)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")

#@gimp Whirl drawing : draw_whirl, gimp_draw_whirl_preview(0)
#@gimp : Amplitude = float(20,0,100)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_draw_whirl_preview :
  -gimp_split_preview "-draw_whirl ${1--2}",$-1

#@gimp _<b>Black &amp; white</b>
#--------------------------------

#@gimp Charcoal : gimp_charcoal, gimp_charcoal_preview(0)
#@gimp : Granularity = int(65,0,800)
#@gimp : Lowlights crossover point = int(70,0,255)
#@gimp : Highlights crossover point = int(170,0,255)
#@gimp : Boost contrast = bool(0)
#@gimp : Resize image for optimum effect = bool(1)
#@gimp : Add chalk highlights = bool(0)
#@gimp : Minimal highlights = int(50,0,255)
#@gimp : Maximal highlights = int(70,0,255)
#@gimp : Background color = color(255,255,255)
#@gimp : Foreground color = color(0,0,0)
#@gimp : Invert background/foreground = bool(0)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2011/03/17</i>.</small>")
#@gimp : note = note("<small>Inspired from the Charcoal script by <i>micomicon</i> :</small>")
#@gimp : link = link("http://registry.gimp.org/node/25078")
gimp_charcoal :
  -repeat @# -l[$>] -split_opacity -l[0]
    -compose_channels max
    w={w} h={h}
    -if $5 -resize[-1] 150%,150%,1,1,6 -endif
    -if $4 -equalize[-1] 256 -n[-1] 0,255 -endif
    -sharpen {$1*3} -cut 0,255
    -if $6 --t2 $7,$8 -endif  # Add highlights layer if required.
    -t2[0] $2,$3
    -if {!$15} -eq[0] 0 -endif
    -or
    --*[0] $10 --*[0] $11 -*[0] $9
    -append[-3--1] c -replace_color 0,0,0,0,0,$12,$13,$14
    -r $w,$h,1,100%,2
  -endl -a c -endl -done

gimp_charcoal_preview :
  -gimp_split_preview "-gimp_charcoal ${1--2}",$-1

#@gimp Hard sketch : gimp_hardsketchbw, gimp_hardsketchbw_preview(0)
#@gimp : Amplitude = float(300,0,4000)
#@gimp : Density = float(50,0,100)
#@gimp : Smoothness = float(1,0,10)
#@gimp : Opacity = float(0.1,0,1)
#@gimp : Edge = float(20,0,100)
#@gimp : Fast approximation = bool(1)
#@gimp : Negative = bool(0)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_hardsketchbw :
  -b $3 -hardsketchbw $1,$2,$4,$5,$6
  -if $7 -negative -endif

gimp_hardsketchbw_preview :
  -gimp_split_preview "-gimp_hardsketchbw ${1--2}",$-1

#@gimp Hough sketch : gimp_houghsketchbw, gimp_houghsketchbw_preview(0)
#@gimp : Smoothness = float(1.25,0,10)
#@gimp : Density = float(10,0,70)
#@gimp : Radius = int(5,0,30)
#@gimp : Threshold = float(80,0,100)
#@gimp : Opacity = float(0.1,0,1)
#@gimp : Negative = bool(0)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2011/05/18</i>.</small>")
gimp_houghsketchbw :
  -b $1 -n 0,255 -houghsketchbw ${2-5}
  -if $6 -negative -endif

gimp_houghsketchbw_preview :
  -gimp_split_preview "-gimp_houghsketchbw ${1--2}",$-1

#@gimp Ink wash : gimp_ink_wash, gimp_ink_wash(0)
#@gimp : note = note("Ink wash controls")
#@gimp : Size = float(0.14,0,4)
#@gimp : Amplitude = float(23,0,200)
#@gimp : sep = separator()
#@gimp : note = note("Check if you wish visual control on this step")
#@gimp : SKIP all other steps = bool(false)
#@gimp : note = note ("UNcheck to reactivate the other controls")
#@gimp : sep = separator()
#@gimp : Smoother Sharpness = float(0.5,0,2)
#@gimp : Smoother Edge Protection = float(0.54,0,1)
#@gimp : Smoother Softness = float(2.25,0,10)
#@gimp : sep = separator()
#@gimp : Stretch Contrast = choice("None","Automatic","Automatic & Contrast Mask","Manual Controls")
#@gimp : note = note ("To activate the sliders below chose 'Manual Controls'")
#@gimp :sep = separator ()
#@gimp : LN Amplititude = float(2,0,60)
#@gimp : LN Size = float(6,0,64)
#@gimp : LN Neightborhood-Smoothness = float(5,0,40)
#@gimp : LN Average-Smoothness = float(20,0,40)
#@gimp : sep = separator(), note = note("<small>Author : <i>PhotoComiX</i>.      Latest update : <i>2011/4/5</i>.</small>")
#@gimp : note = link(0,"Forum thread about the filter discussion","http://gimpchat.com/viewtopic.php?f=10&t=914")
gimp_ink_wash :
  -repeat @# -l[$>] -split_opacity -l[0]
    -gimp_pencilbw[-1] $1,$2,0,0,0
    -if {$3==1} -continue
    -elif {$3==0} -gimp_anisotropic_smoothing[-1] 60,$4,$5,$6,1.1,0.8,30,2,0,1,1,0,1,0
    -endif
    -if {$7==1} -normalize_local[-1] 2,6,5,24,1,0,255
	-elif {$7==2}  -normalize_local[-1] 2,6,5,24,1,0,255 -gimp_contrast_swm 2,0,0.512
    -elif {$7==3} -gimp_normalize_local[-1] $8,$9,$10,$11,1,3,0
    -endif
  -endl -a c -endl -done

#@gimp Pencil : gimp_pencilbw, gimp_pencilbw_preview(0)
#@gimp : Size = float(0.3,0,5)
#@gimp : Amplitude = float(60,0,200)
#@gimp : Hue = float(0,0,360)
#@gimp : Saturation = float(0,0,1)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_pencilbw :
  -pencilbw $1,$2
  -if {$3||$4} -/ 255 -repeat @# -i[-2] 100%,100%,1,1,$4 -i[-3] 100%,100%,1,1,$3 -a[-3--1] c -hsv2rgb[-1] -mv[-1] 0 -done -endif

gimp_pencilbw_preview :
  -gimp_split_preview "-gimp_pencilbw ${1--2}",$-1

#@gimp Sketch : gimp_sketchbw, gimp_sketchbw_preview(0)
#@gimp : Number of orientations = int(2,1,16)
#@gimp : Starting angle = float(45,0,180)
#@gimp : Angle range = float(180,0,180)
#@gimp : Stroke length = float(30,0,1000)
#@gimp : Contour threshold = float(1,0,3)
#@gimp : Opacity = float(0.03,0,0.3)
#@gimp : Background intensity = float(0,0,2)
#@gimp : Density = float(0.6,0,5)
#@gimp : Sharpness = float(0.1,0,1.5)
#@gimp : Anisotropy = float(0.6,0,1)
#@gimp : Smoothness = float(0.25,0,10)
#@gimp : Coherence = float(1,0,10)
#@gimp : Boost stroke = bool(0)
#@gimp : Curved stroke = bool(1)
#@gimp : Color model = choice("Black on white","White on black","Black on transparent white","White on transparent black")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_sketchbw :
  -sketchbw ${1-14}
  -if {$15&1} -negative -endif
  -if {$15==2} -r 100%,100%,1,4 -repeat @# -sh[$>] 3,3 -*[-1] -2 -+[-1] {2*255} -c[-1] 0,255 -rm[-1] -done
  -elif {$15==3} -r 100%,100%,1,4 -repeat @# -sh[$>] 3,3 -*[-1] 2 -c[-1] 0,255 -rm[-1] -done
  -endif

gimp_sketchbw_preview :
  -gimp_split_preview "-gimp_sketchbw ${1--2}",$-1

#@gimp Stamp : gimp_stamp, gimp_stamp_preview(0)
#@gimp : Auto-threshold = bool(1)
#@gimp : Threshold = int(50,0,100)
#@gimp : Smoothness = float(0,0,10)
#@gimp : Sharpening = float(0,0,30)
#@gimp : Invert colors = bool(false)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Authors : <i>Antaron, Mahvin, David Tschumperl&#233;</i>.             Latest update : 2011/05/17.</small>")
gimp_stamp :
  -norm
  -if $1 -otsu 256 -else -t $2% -endif
  -b $3,0 -sharpen $4 -n 0,255
  -apply_curve 1,0,0,101,33,170,229,255,255
  -if $5 -negative -endif
  -to_rgb

gimp_stamp_preview :
  -gimp_split_preview "-gimp_stamp ${1--2}",$-1

#@gimp Stencil : gimp_stencilbw, gimp_stencilbw_preview(0)
#@gimp : Threshold = float(10,0,30)
#@gimp : Smoothness = float(10,0,30)
#@gimp : Hue = float(0,0,360)
#@gimp : Saturation = float(0,0,1)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_stencilbw :
  -stencilbw $1,$2
  -if {$3||$4} -/ 255 -repeat @# -i[-2] 100%,100%,1,1,$4 -i[-3] 100%,100%,1,1,$3 -a[-3--1] c -hsv2rgb[-1] -mv[-1] 0 -done -endif

gimp_stencilbw_preview :
  -gimp_split_preview "-gimp_stencilbw ${1--2}",$-1

#@gimp Steampunk-Pencil : gimp_steampunk, gimp_steampunk_preview(0)
#@gimp : sep = separator()
#@gimp : Radius = float(0.95,0,4)
#@gimp : Amplitude = float(14,0,200)
#@gimp : Iterations = int(2,1,20)
#@gimp : Steam Pressure = int(2,1,30)
#@gimp : Lubrication = float(0.9,0,1.9)
#@gimp : sep = separator()
#@gimp : Contrast FX = choice("None-Skip","L Normalization","Mask","Boost","Fast Tone Map")
#@gimp : Equalize = bool(true)
#@gimp : sep = separator()
#@gimp : note = note(" For a more "painted" effect")
#@gimp : Add Painter's Touch = bool(false)
#@gimp : note = note("If unchecked the 3 sliders below are disabled")
#@gimp : sep = separator ()
#@gimp : Painter's Touch Sharpness = float(0.5,0,2)
#@gimp : Painter's Edge Protection Flow = float(0.75,0,1)
#@gimp : Painter's Smoothness = float(0.48,0,10)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>PhotoComiX</i>.      Latest update : <i>2011/6/29 </i>.</small>")
gimp_steampunk :
  -repeat @# -l[$>] -split_opacity -l[0]
    -gimp_pencilbw $1,$2,0,0,0
    -gimp_kuwahara $3,$4,0,0
    -blur_xy $5
    -if {$6==1} -gimp_normalize_local 4.8,22,6.89,20,1,3,0
    -elif {$6==2} -gimp_contrast_swm 2,0,1
    -elif {$6==3} -gimp_contrast_swm 2,1,1
    -elif {$6==4} -gimp_map_tones_fast 3,0.5,3, -endif
    -if {$7==1} -equalize 255 -endif
    -if {$8==1} -gimp_anisotropic_smoothing 60,$9,$10,$11,1.1,0.8,30,2,0,1,1,0,1,0 -endif
  -endl -a c -endl -done

gimp_steampunk_preview :
  -gimp_split_preview "-gimp_steampunk ${1--2}",$-1


#@gimp _<b>Colors</b>
#---------------------

#@gimp RGB mixer : gimp_mix_rgb, gimp_mix_rgb_preview(1)
#@gimp : Red contrast = float(1,0,4)
#@gimp : Red brightness = float(0,-255,255)
#@gimp : Red smoothness = float(0,0,10)
#@gimp : Green contrast = float(1,0,4)
#@gimp : Green brightness = float(0,-255,255)
#@gimp : Green smoothness = float(0,0,10)
#@gimp : Blue contrast = float(1,0,4)
#@gimp : Blue brightness = float(0,-255,255)
#@gimp : Blue smoothness = float(0,0,10)
#@gimp : note = note()
#@gimp : Tones range = choice("All tones","Shadows","Mid-tones","Highlights")
#@gimp : Tones smoothness = float(2,0,10)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_start_mix :
  -if {$1==1} --tones[-1] 3 -+[-2,-1] -b[-2,-1] $2% -r[-2,-1] [-3] -*[-1] [-3] -mv[-3] @#
  -elif {$1==2} --tones[-1] 3 -+[-3,-1] -b[-2,-1] $2% -r[-2,-1] [-3] -*[-2] [-3] -mv[-3] @#
  -elif {$1==3} --tones[-1] 3 -+[-3,-2] -b[-2,-1] $2% -r[-2,-1] [-3] -*[-2] [-3] -mv[-3] @#
  -endif
gimp_end_mix :
  -if {$1==1} -*[-3,-1] -+[-2,-1]
  -elif {$1==2} -*[-2,-1] -+[-2,-1]
  -elif {$1==3} -*[-2,-1] -+[-2,-1]
  -endif

gimp_mix_rgb :
  -repeat @# -l[-1] -split_opacity -rv -to_rgb[-1]
    -gimp_start_mix $10,$11
    --[-1] 128 -s[-1] c
    -*[-3] $1 -+[-3] $2 -b[-3] $3%
    -*[-2] $4 -+[-2] $5 -b[-2] $6%
    -*[-1] $7 -+[-1] $8 -b[-1] $9%
    -a[-3--1] c -+[-1] 128 -c[-1] 0,255
    -gimp_end_mix $10
  -if {@#!=3} -rv -a c -endif -endl -mv[-1] 0 -done

gimp_mix_rgb_preview :
  -gimp_split_preview "-gimp_mix_rgb ${1--2}",$-1

#@gimp YCbCr mixer : gimp_mix_ycbcr, gimp_mix_ycbcr_preview(1)
#@gimp : Luminance contrast = float(1,0,4)
#@gimp : Luminance brightness = float(0,-255,255)
#@gimp : Luminance smoothness = float(0,0,10)
#@gimp : Blue chroma contrast = float(1,0,4)
#@gimp : Blue chroma brightness = float(0,-255,255)
#@gimp : Blue chroma smoothness = float(0,0,10)
#@gimp : Red chroma contrast = float(1,0,4)
#@gimp : Red chroma brightness = float(0,-255,255)
#@gimp : Red chroma smoothness = float(0,0,10)
#@gimp : note = note()
#@gimp : Tones range = choice("All tones","Shadows","Mid-tones","Highlights")
#@gimp : Tones smoothness = float(2,0,10)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_mix_ycbcr :
  -repeat @# -l[-1] -split_opacity -rv -to_rgb[-1]
    -gimp_start_mix $10,$11
    -rgb2ycbcr[-1] --[-1] 128 -s[-1] c
    -*[-3] $1 -+[-3] $2 -b[-3] $3%
    -*[-2] $4 -+[-2] $5 -b[-2] $6%
    -*[-1] $7 -+[-1] $8 -b[-1] $9%
    -a[-3--1] c -+[-1] 128 -c[-1] 0,255 -ycbcr2rgb[-1]
    -gimp_end_mix $10
  -if {@#!=3} -rv -a c -endif -endl -mv[-1] 0 -done

gimp_mix_ycbcr_preview :
  -gimp_split_preview "-gimp_mix_ycbcr ${1--2}",$-1

#@gimp HSV mixer : gimp_mix_hsv, gimp_mix_hsv_preview(1)
#@gimp : Hue contrast = float(1,0,4)
#@gimp : Hue brightness = float(0,-180,180)
#@gimp : Hue smoothness = float(0,0,10)
#@gimp : Saturation contrast = float(1,0,4)
#@gimp : Saturation brightness = float(0,-1,1)
#@gimp : Saturation smoothness = float(0,0,10)
#@gimp : Value contrast = float(1,0,4)
#@gimp : Value brightness = float(0,-1,1)
#@gimp : Value smoothness = float(0,0,10)
#@gimp : note = note()
#@gimp : Tones range = choice("All tones","Shadows","Mid-tones","Highlights")
#@gimp : Tones smoothness = float(2,0,10)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_mix_hsv :
  -repeat @# -l[-1] -split_opacity -rv -to_rgb[-1]
    -gimp_start_mix $10,$11
    -rgb2hsv[-1] -s[-1] c --[-2,-1] 0.5
    -*[-3] $1 -+[-3] $2 -b[-3] $3%
    -*[-2] $4 -+[-2] $5 -b[-2] $6%
    -*[-1] $7 -+[-1] $8 -b[-1] $9%
    -%[-3] 360 -+[-2,-1] 0.5 -c[-2,-1] 0,1 -a[-3--1] c -hsv2rgb[-1]
    -gimp_end_mix $10
  -if {@#!=3} -rv -a c -endif -endl -mv[-1] 0 -done

gimp_mix_hsv_preview :
  -gimp_split_preview "-gimp_mix_hsv ${1--2}",$-1

#@gimp Lab mixer : gimp_mix_lab, gimp_mix_lab_preview(1)
#@gimp : Lightness contrast = float(1,0.5,1.5)
#@gimp : Lightness brightness = float(0,-50,50)
#@gimp : Lightness smoothness = float(0,0,10)
#@gimp : A-color contrast = float(1,0,4)
#@gimp : A-color brightness = float(0,-20,20)
#@gimp : A-color smoothness = float(0,0,10)
#@gimp : B-color contrast = float(1,0,4)
#@gimp : B-color brightness = float(0,-20,20)
#@gimp : B-color smoothness = float(0,0,10)
#@gimp : note = note()
#@gimp : Tones range = choice("All tones","Shadows","Mid-tones","Highlights")
#@gimp : Tones smoothness = float(2,0,10)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_mix_lab :
  -repeat @# -l[-1] -split_opacity -rv -to_rgb[-1]
    -gimp_start_mix $10,$11
    -rgb2lab[-1] -s[-1] c
    -*[-3] $1 -+[-3] $2 -b[-3] $3%
    -*[-2] $4 -+[-2] $5 -b[-2] $6%
    -*[-1] $7 -+[-1] $8 -b[-1] $9%
    -a[-3--1] c -lab2rgb[-1]
    -gimp_end_mix $10
  -if {@#!=3} -rv -a c -endif -endl -mv[-1] 0 -done

gimp_mix_lab_preview :
  -gimp_split_preview "-gimp_mix_lab ${1--2}",$-1

#@gimp CMYK mixer : gimp_mix_cmyk, gimp_mix_cmyk_preview(1)
#@gimp : Cyan contrast = float(1,0,4)
#@gimp : Cyan brightness = float(0,-255,255)
#@gimp : Cyan smoothness = float(0,0,10)
#@gimp : Magenta contrast = float(1,0,4)
#@gimp : Magenta brightness = float(0,-255,255)
#@gimp : Magenta smoothness = float(0,0,10)
#@gimp : Yellow contrast = float(1,0,4)
#@gimp : Yellow brightness = float(0,-255,255)
#@gimp : Yellow smoothness = float(0,0,10)
#@gimp : Key contrast = float(1,0,4)
#@gimp : Key brightness = float(0,-255,255)
#@gimp : Key smoothness = float(0,0,10)
#@gimp : note = note()
#@gimp : Tones range = choice("All tones","Shadows","Mid-tones","Highlights")
#@gimp : Tones smoothness = float(2,0,10)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_mix_cmyk :
  -repeat @# -l[-1] -split_opacity -rv -to_rgb[-1]
    -gimp_start_mix $13,$14
    -rgb2cmyk[-1] -s[-1] c
    -*[-4] $1 -+[-4] $2 -b[-4] $3%
    -*[-3] $4 -+[-3] $5 -b[-3] $6%
    -*[-2] $7 -+[-2] $8 -b[-2] $9%
    -*[-1] $10 -+[-1] $11 -b[-1] $12%
    -a[-4--1] c -cmyk2rgb[-1]
    -gimp_end_mix $13
  -if {@#!=3} -rv -a c -endif -endl -mv[-1] 0 -done

gimp_mix_cmyk_preview :
  -gimp_split_preview "-gimp_mix_cmyk ${1--2}",$-1

#@gimp HSV Equalizer : gimp_hsv_equalizer, gimp_hsv_equalizer_preview
#@gimp : Preview bands = bool(false)
#@gimp : sep = separator()
#@gimp : Hue band = float(180,0,360)
#@gimp : Band width = float(40,1,360)
#@gimp : Hue shift = float(0,-180,180)
#@gimp : Saturation correction = float(0,-0.99,0.99)
#@gimp : Value correction = float(0,-0.99,0.99)
#@gimp : sep = separator()
#@gimp : Hue band = float(180,0,360)
#@gimp : Band width = float(40,1,360)
#@gimp : Hue shift = float(0,-180,180)
#@gimp : Saturation correction = float(0,-0.99,0.99)
#@gimp : Value correction = float(0,-0.99,0.99)
#@gimp : sep = separator()
#@gimp : Hue band = float(180,0,360)
#@gimp : Band width = float(40,1,360)
#@gimp : Hue shift = float(0,-180,180)
#@gimp : Saturation correction = float(0,-0.99,0.99)
#@gimp : Value correction = float(0,-0.99,0.99)
#@gimp : sep = separator()
#@gimp : note = note("<small>Author : <i>J&#233;rome Ferrari</i>.      Latest update : <i>2011/01/14</i>.</small>")
#@gimp : note = link("Filter explained here","http://www.flickr.com/groups/gmic/discuss/72157625798533482")
gimp_hsv_equalizer :
  -repeat @# -local[@{>,-1}]
  -to_rgb -rgb2hsv -split c
# From now on 0,1,2 are H,S,V
#3 masks:
  --fill[0] if(abs(i-$2)<$3/2|abs(i-$2-360)<$3/2|abs(i-$2+360)<$3/2,1,0)
  --fill[0] if(abs(i-$7)<$8/2|abs(i-$7-360)<$8/2|abs(i-$7+360)<$8/2,1,0)
  --fill[0] if(abs(i-$12)<$13/2|abs(i-$12-360)<$13/2|abs(i-$12+360)<$13/2,1,0)
# From now on 3,4,5 are Masks
  --threshold[1,2] 0.01 -*[-1,-2] [-1]x2 -*[-1,3] -*[-1,4] -*[-1,5]	#0 saturation and value not in mask
# Hue shift:
  --*[3] $4 --*[4] $9 --*[5] $14 -+[-1,-2,-3]
  -+[-1,0] -%[0] 360
# Saturation :
  -if {$5>=0} --*[3] -$5 -else --*[3] {1/(1+$5)-1} -endif -+[-1] 1
  -if {$10>=0} --*[4] -$10 -else --*[4] {1/(1+$10)-1} -endif -+[-1] 1
  -if {$15>=0} --*[5] -$15 -else --*[5] {1/(1+$15)-1} -endif -+[-1] 1
  -*[-1,-2,-3] -^[1,-1]
# Value :
  -if {$6>=0} --*[3] -$6 -else --*[3] {1/(1+$6)-1} -endif -+[-1] 1
  -if {$11>=0} --*[4] -$11 -else --*[4] {1/(1+$11)-1} -endif -+[-1] 1
  -if {$16>=0} --*[5] -$16 -else --*[5] {1/(1+$16)-1} -endif -+[-1] 1
  -*[-1,-2,-3] -^[2,-1]
#reconstruction
  -rm[3,4,5] -append[0,1,2] c -hsv2rgb
  -endlocal -done

gimp_hsv_equalizer_preview :
-local[-1]
  -if {$1==0} -gimp_hsv_equalizer $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16
  -else
    -to_rgb -rgb2hsv -split c
    (0,359) -resize[-1] [-2],{@{0,h}/10},1,1,3 [-1] -fill[-1] 1	#create lower band
    -j[0] [3],0,91% -j[1] [4],0,91% -j[2] [4],0,91% -rm[-1,-2] #paste lower band
    --fill[0] if(abs(i-$2)<$3/2|abs(i-$2-360)<$3/2|abs(i-$2+360)<$3/2,1,0)
    --fill[0] if(abs(i-$7)<$8/2|abs(i-$7-360)<$8/2|abs(i-$7+360)<$8/2,1,0)
    --fill[0] if(abs(i-$12)<$13/2|abs(i-$12-360)<$13/2|abs(i-$12+360)<$13/2,1,0) #masks
    -or[-3--1] -+[-1] 0.33 -/[-1] 1.33	#1 and 0.25
    -*[2,-1] -append c -hsv2rgb
  -endif
-endlocal

#@gimp Boost / Fade : gimp_boost_fade, gimp_boost_fade_preview
#@gimp : Amplitude = float(5,0,10)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2011/10/12</i>.</small>")
gimp_boost_fade :
  -i[0] 640,480,1,3 -rand[0] 0,1 -b[0] {10-$1} -n[0] 0,255 -transfer_colors -rm[0]

gimp_boost_fade_preview :
  -gimp_split_preview "-gimp_boost_fade ${1--2}",$-1

#@gimp Color balance : gimp_balance_gamma, gimp_balance_gamma_preview
#@gimp : Neutral color = color(128,128,128)
#@gimp : Stretch colors = bool(1)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2011/07/01</i>.</small>")
gimp_balance_gamma :
  -balance_gamma ${1-3}
  -if $4 -repeat @# -l[$>] -s c -n 0,255 -a c -endl -done -endif

gimp_balance_gamma_preview :
  -gimp_split_preview "-gimp_balance_gamma ${1--2}",$-1

#@gimp Channel processing : gimp_channel_processing, gimp_channel_processing_preview(1)
#@gimp : Gamma = float(1,0.01,5)
#@gimp : Contrast = float(1,0,4)
#@gimp : Brightness = float(0,-255,255)
#@gimp : Smoothness = float(0,0,10)
#@gimp : Value action = choice("None","Cut","Cut & Normalize","Normalize","Threshold")
#@gimp : Low value = float(0,0,100)
#@gimp : High value = float(100,0,100)
#@gimp : Quantization = int(256,1,256)
#@gimp : Equalization = bool()
#@gimp : Negation = bool()
#@gimp : note = note()
#@gimp : Tones range = choice("All tones","Shadows","Mid-tones","Highlights")
#@gimp : Tones smoothness = float(2,0,10)
#@gimp : note = note()
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
_gimp_channel_processing :
  -apply_gamma[-1] $1
  -if {$2!=1} --[-1] 128 -*[-1] $2 -+[-1] 128 -endif
  -+[-1] $3
  -b[-1] $4% -c[-1] 0,255
  -if {$5==1} -c[-1] $6%,$7%
  -elif {$5==2} -c[-1] $6%,$7% -n[-1] 0,255
  -elif {$5==3} -n[-1] $6%,$7%
  -elif {$5==4} -t2[-1] $6%,$7% -*[-1] 255
  -endif
  -if {$8!=256} -quantize[-1] $8 -endif
  -if $9 -equalize[-1] 256 -endif
  -if $10 -negative[-1] -endif

gimp_channel_processing :
  -repeat @# -l[-1] -split_opacity -rv -to_rgb[-1]
    -gimp_start_mix $11,$12
    -apply_channels[-1] "-_gimp_channel_processing $1,$2,$3,$4,$5,$6,$7,$8,$9,$10",$13,0
    -gimp_end_mix $11
  -if {@#!=3} -rv -a c -endif -endl -mv[-1] 0 -done

gimp_channel_processing_preview :
  -gimp_split_preview "-gimp_channel_processing ${1--2}",$-1

#@gimp Decompose channels : gimp_decompose_channels, gimp_decompose_channels_preview
#@gimp : Color basis = choice(7,"RGB","HSV","HSL","HSI","YUV","YCbCr","XYZ","Lab","Lch","CMY","CMYK")
#@gimp : Action = choice("Decompose","Recompose")
#@gimp : Use multiple layers = bool(0)
#@gimp : Include opacity layer = bool(1)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_decompose_channels :
  -if {!$2} # Decompose
    -if $4 -to_rgba -else -to_rgb -endif
    -repeat @# -l[-1]
      -split_opacity -_gimp_decompose_channels$1[0]
      -s[0] c -if {!$3} -a x -endif
      nb=@#
    -endl -mv[-$nb--1] 0 -done
  -else # Recompose
    -channels 0 nbc={3+($1==10)} nb={$nbc+$4}
    -if $3 -repeat {int(@#/$nb)} -l[0-{$nb-1}]
      -a[0-{$nbc-1}] c -_gimp_recompose_channels$1[0] -a c
    -endl -mv[-1] 0 -done
    -else -repeat @# -l[$>]
      -s x,$nb -a[0-{$nbc-1}] c -_gimp_recompose_channels$1[0] -a c
    -endl -mv[-1] 0 -done -endif
  -endif

gimp_decompose_channels_preview :
  -gimp_decompose_channels ${^0} -a x

_gimp_decompose_channels0 :
_gimp_decompose_channels1 : -rgb2hsv8
_gimp_decompose_channels2 : -rgb2hsl8
_gimp_decompose_channels3 : -rgb2hsi8
_gimp_decompose_channels4 : -rgb2yuv8
_gimp_decompose_channels5 : -rgb2ycbcr
_gimp_decompose_channels6 : -rgb2xyz8
_gimp_decompose_channels7 : -rgb2lab8
_gimp_decompose_channels8 : -rgb2lch8
_gimp_decompose_channels9 : -rgb2cmy
_gimp_decompose_channels10 : -rgb2cmyk

_gimp_recompose_channels0 :
_gimp_recompose_channels1 : -hsv82rgb
_gimp_recompose_channels2 : -hsl82rgb
_gimp_recompose_channels3 : -hsi82rgb
_gimp_recompose_channels4 : -yuv82rgb
_gimp_recompose_channels5 : -ycbcr2rgb
_gimp_recompose_channels6 : -xyz82rgb
_gimp_recompose_channels7 : -lab82rgb
_gimp_recompose_channels8 : -lch82rgb
_gimp_recompose_channels9 : -cmy2rgb
_gimp_recompose_channels10 : -cmyk2rgb

#@gimp Discrete color square: gimp_colorsquare, gimp_colorsquare
#@gimp : a = color(0,0,0)
#@gimp : b = color(255,255,255)
#@gimp : c = color(128,255,192)
#@gimp : d = color(80,128,255)
#@gimp : Colorspace = choice("LCH","LAB","YCbCr","RGB")
#@gimp : sep = separator()
#@gimp : Quantization = int(256,2,256)
#@gimp : Disable quantization = bool(0)
#@gimp : Clip high end = bool(0)
#@gimp : Steps = int(5,3,32)
#@gimp : Scale = int(36,1,96)
#@gimp : sep = separator(), note = note("<small>Author : <i>Noun0ion9</i>.      Latest update : <i>2011/05/18</i>.</small>")
gimp_colorsquare:
  -rm
  ($1,$4;$7,$10^$2,$5;$8,$11^$3,$6;$9,$12)
  -to_rgb
  -srgb2rgb
  -if {$13==3}
     -resize $17,$17,1,3,3,0
  -elif {$13==0}
     -rgb2lch -resize $17,$17,1,3,3,0 -lch2rgb
  -elif {$13==1}
     -rgb2lab -resize $17,$17,1,3,3,0 -lab2rgb
  -elif {$13==2}
     -rgb2ycbcr -resize $17,$17,1,3,3,0 -ycbcr2rgb
  -endif
  -rgb2srgb
  -if {$14!=256}
     -if {$15==0}
       -if {$16==1}
         -quantize {$14+1},0
         -cut 0,{$14-1}
         -* {256/$14}
       -else
         -quantize $14,0
         -* {255/($14-1)}
       -endif
     -endif
  -endif
  -resize {$17*$18},{$17*$18},1,3,1,0,0,0,0,0

#@gimp Curves : gimp_apply_curve, gimp_apply_curve_preview
#@gimp : Starting Y = int(0,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(1) = int(-1,-1,255)
#@gimp : Y-coord(1) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(2) = int(-1,-1,255)
#@gimp : Y-coord(2) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(3) = int(-1,-1,255)
#@gimp : Y-coord(3) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(4) = int(-1,-1,255)
#@gimp : Y-coord(4) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(5) = int(-1,-1,255)
#@gimp : Y-coord(5) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : Ending Y = int(255,0,255)
#@gimp : sep = separator()
#@gimp : Curve smoothness = float(1,0,1)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : Value range = choice("Cut","Normalize")
#@gimp : Display histogram = float(0,0,100)
#@gimp : Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_apply_curve :
  -apply_channels "-_gimp_apply_curve ${1-13}",$14,$15

_gimp_apply_curve :
  -apply_curve $13,0,$1,\
                   @{"-if {$2>=0} -u $2,$3, -else -u \"\" -endif"}\
                   @{"-if {$4>=0} -u $4,$5, -else -u \"\" -endif"}\
                   @{"-if {$6>=0} -u $6,$7, -else -u \"\" -endif"}\
                   @{"-if {$8>=0} -u $8,$9, -else -u \"\" -endif"}\
                   @{"-if {$10>=0} -u $10,$11, -else -u \"\" -endif"}\
                   255,$12

gimp_apply_curve_preview :
  -function1d $13,0,$1,\
                  @{"-if {$2>=0} -u $2,$3, -else -u \"\" -endif"}\
                  @{"-if {$4>=0} -u $4,$5, -else -u \"\" -endif"}\
                  @{"-if {$6>=0} -u $6,$7, -else -u \"\" -endif"}\
                  @{"-if {$8>=0} -u $8,$9, -else -u \"\" -endif"}\
                  @{"-if {$10>=0} -u $10,$11, -else -u \"\" -endif"}\
                  255,$12
  -mv[-1] 0
  -repeat {@#-1}
    --gimp_split_preview[-1] "-gimp_apply_curve ${1--2}",$-1
    -axes[-1] 0,255,255,0,13,1,255 -grid[-1] 10%,10%,0,0,0.3,0xCCCCCCCC,255
    -line[-1] 0,100%,100%,0,0.3,0xCCCCCCCC,255
    -if $-2
      [-1],[-1],1,1,-{$-2*255/100} -to_gray[-3] -histogram[-3] 256,0,255 -graph[-1] [-3],3,0,0,0,1,0
      -rm[-3] -+[-1] {$-2*255/100} -+[-2,-1] -c[-1] 0,255
     -else -rm[-2] -endif
     -graph[-1] [0],1,0,255,0,1,255
     -_gimp_apply_curve_preview 0,$1,0 -_gimp_apply_curve_preview $2,$3,1
     -_gimp_apply_curve_preview $4,$5,2 -_gimp_apply_curve_preview $6,$7,3
     -_gimp_apply_curve_preview $8,$9,4 -_gimp_apply_curve_preview $10,$11,5
     -_gimp_apply_curve_preview 255,$12,6
  -mv[-1] 1 -done -rm[0]

_gimp_apply_curve_preview :
  -if {$1>=0}
    x={$1*100/255}% y={100-$2*100/255}%
    -ellipse[-1] $x,$y,3,3,0,1,0xFFFFFFFF,0,0,0 -ellipse[-1] $x,$y,2,2,0,1,0,255,0
    -text[-1] $3,$x,{$y*h-20},13,1,255
  -endif

#@gimp RGB Curves
#@gimp Red : gimp_apply_RGBcurve, gimp_apply_Rcurve_preview
#@gimp : Starting Y = int(0,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(1) = int(-1,-1,255)
#@gimp : Y-coord(1) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(2) = int(-1,-1,255)
#@gimp : Y-coord(2) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(3) = int(-1,-1,255)
#@gimp : Y-coord(3) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(4) = int(-1,-1,255)
#@gimp : Y-coord(4) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(5) = int(-1,-1,255)
#@gimp : Y-coord(5) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : Ending Y = int(255,0,255)
#@gimp : sep = separator()
#@gimp : Curve smoothness = float(1,0,1)
#@gimp : Display histogram = float(0,0,100)
#@gimp : Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")

#@gimp Green : gimp_apply_RGBcurve, gimp_apply_Gcurve_preview
#@gimp : Starting Y = int(0,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(1) = int(-1,-1,255)
#@gimp : Y-coord(1) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(2) = int(-1,-1,255)
#@gimp : Y-coord(2) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(3) = int(-1,-1,255)
#@gimp : Y-coord(3) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(4) = int(-1,-1,255)
#@gimp : Y-coord(4) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(5) = int(-1,-1,255)
#@gimp : Y-coord(5) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : Ending Y = int(255,0,255)
#@gimp : sep = separator()
#@gimp : Curve smoothness = float(1,0,1)
#@gimp : Display histogram = float(0,0,100)
#@gimp : Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")

#@gimp Blue : gimp_apply_RGBcurve, gimp_apply_Bcurve_preview
#@gimp : Starting Y = int(0,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(1) = int(-1,-1,255)
#@gimp : Y-coord(1) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(2) = int(-1,-1,255)
#@gimp : Y-coord(2) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(3) = int(-1,-1,255)
#@gimp : Y-coord(3) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(4) = int(-1,-1,255)
#@gimp : Y-coord(4) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(5) = int(-1,-1,255)
#@gimp : Y-coord(5) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : Ending Y = int(255,0,255)
#@gimp : sep = separator()
#@gimp : Curve smoothness = float(1,0,1)
#@gimp : Display histogram = float(0,0,100)
#@gimp : Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_apply_RGBcurve : -skip $1
  -gimp_apply_RGBcurve_configfile
  -repeat {@#-1} -l[$>,-1]
    -to_colormode[0] {max(3,s)}
    -sh[0] 0,0 -_gimp_apply_RGBcurve[-1] @{-2,0-12} -rm[-1]
    -sh[0] 1,1 -_gimp_apply_RGBcurve[-1] @{-2,13-25} -rm[-1]
    -sh[0] 2,2 -_gimp_apply_RGBcurve[-1] @{-2,26-38} -rm[-1]
  -endl -done
  -rm[-1]

_gimp_apply_RGBcurve :
  -apply_curve $13,0,$1,\
                   @{"-if {$2>=0} -u $2,$3, -else -u \"\" -endif"}\
                   @{"-if {$4>=0} -u $4,$5, -else -u \"\" -endif"}\
                   @{"-if {$6>=0} -u $6,$7, -else -u \"\" -endif"}\
                   @{"-if {$8>=0} -u $8,$9, -else -u \"\" -endif"}\
                   @{"-if {$10>=0} -u $10,$11, -else -u \"\" -endif"}\
                   255,$12
  -c 0,255

gimp_apply_Rcurve_preview :
  -gimp_apply_RGBcurve_configfile
  -sh[-1] 0,0,0,0 -f[-1] ${1--3} -rm[-1]
  -gimp_apply_RGBcurve_preview[0--2] @-1,0,${-2,-1} -rm[-1]

gimp_apply_Gcurve_preview :
  -gimp_apply_RGBcurve_configfile
  -sh[-1] 1,1,0,0 -f[-1] ${1--3} -rm[-1]
  -gimp_apply_RGBcurve_preview[0--2] @-1,1,${-2,-1} -rm[-1]

gimp_apply_Bcurve_preview :
  -gimp_apply_RGBcurve_configfile
  -sh[-1] 2,2,0,0 -f[-1] ${1--3} -rm[-1]
  -gimp_apply_RGBcurve_preview[0--2] @-1,2,${-2,-1} -rm[-1]

gimp_apply_RGBcurve_configfile :
  filename=@{-path_tmp}/.gmic_RGBcurve.dlm
  -if $filename $filename -else (0,-1,128,-1,128,-1,128,-1,128,-1,128,255,1) -r[-1] 100%,3 -endif

gimp_apply_RGBcurve_preview :
  (${1--3}) -r[-1] 13,3,1,1,-1 -o[-1] @{-path_tmp}/.gmic_RGBcurve.dlm -rm[-1]
  -function1d $13,0,$1,\
                  @{"-if {$2>=0} -u $2,$3, -else -u \"\" -endif"}\
                  @{"-if {$4>=0} -u $4,$5, -else -u \"\" -endif"}\
                  @{"-if {$6>=0} -u $6,$7, -else -u \"\" -endif"}\
                  @{"-if {$8>=0} -u $8,$9, -else -u \"\" -endif"}\
                  @{"-if {$10>=0} -u $10,$11, -else -u \"\" -endif"}\
                  255,$12
  -function1d $26,0,$14,\
                  @{"-if {$15>=0} -u $15,$16, -else -u \"\" -endif"}\
                  @{"-if {$17>=0} -u $17,$18, -else -u \"\" -endif"}\
                  @{"-if {$19>=0} -u $19,$20, -else -u \"\" -endif"}\
                  @{"-if {$21>=0} -u $21,$22, -else -u \"\" -endif"}\
                  @{"-if {$23>=0} -u $23,$24, -else -u \"\" -endif"}\
                  255,$25
  -function1d $39,0,$27,\
                  @{"-if {$28>=0} -u $28,$29, -else -u \"\" -endif"}\
                  @{"-if {$30>=0} -u $30,$31, -else -u \"\" -endif"}\
                  @{"-if {$32>=0} -u $32,$33, -else -u \"\" -endif"}\
                  @{"-if {$34>=0} -u $34,$35, -else -u \"\" -endif"}\
                  @{"-if {$36>=0} -u $36,$37, -else -u \"\" -endif"}\
                  255,$38
  -a[-3--1] y -mv[-1] 0
  -repeat {@#-1}
    [-1]
    --gimp_split_preview[-1] "-gimp_apply_RGBcurve 0",$-1
    -axes[-1] 0,255,255,0,13,1,255 -grid[-1] 10%,10%,0,0,0.3,0xCCCCCCCC,255
    -line[-1] 0,100%,100%,0,0.3,0xCCCCCCCC,255
     -if $-2
        [-1],[-1],1,1,-{$-2*255/100} -to_gray[-3] -histogram[-3] 256,0,255 -graph[-1] [-3],3,0,0,0,1,0
        -rm[-3] -+[-1] {$-2*255/100} -+[-2,-1] -c[-1] 0,255
     -else -rm[-2] -endif
     -line[-1] 0,100%,100%,0,0.3,0xCCCCCCCC,255
     -sh[0] 0,0,0,0
     -graph[-2] [-1],1,0,255,0,1,255,128,128 --[-1] 1
     -graph[-2] [-1],1,0,255,0,0.5,200,0,0 -rm[-1]
     -sh[0] 1,1,0,0
     -graph[-2] [-1],1,0,255,0,1,128,255,128 --[-1] 1
     -graph[-2] [-1],1,0,255,0,0.5,0,200,0 -rm[-1]
     -sh[0] 2,2,0,0
     -graph[-2] [-1],1,0,255,0,1,128,128,255 --[-1] 1
     -graph[-2] [-1],1,0,255,0,0.5,0,0,200 -rm[-1]
     -if {$40==0}
       -_gimp_apply_curve_preview 0,$1,0 -_gimp_apply_curve_preview $2,$3,1
       -_gimp_apply_curve_preview $4,$5,2 -_gimp_apply_curve_preview $6,$7,3
       -_gimp_apply_curve_preview $8,$9,4 -_gimp_apply_curve_preview $10,$11,5
       -_gimp_apply_curve_preview 255,$12,6
     -elif {$40==1}
       -_gimp_apply_curve_preview 0,$14,0 -_gimp_apply_curve_preview $15,$16,1
       -_gimp_apply_curve_preview $17,$18,2 -_gimp_apply_curve_preview $19,$20,3
       -_gimp_apply_curve_preview $21,$22,4 -_gimp_apply_curve_preview $23,$24,5
       -_gimp_apply_curve_preview 255,$25,6
     -else
       -_gimp_apply_curve_preview 0,$27,0 -_gimp_apply_curve_preview $28,$29,1
       -_gimp_apply_curve_preview $30,$31,2 -_gimp_apply_curve_preview $32,$33,3
       -_gimp_apply_curve_preview $34,$35,4 -_gimp_apply_curve_preview $36,$37,5
       -_gimp_apply_curve_preview 255,$38,6
     -endif
  -mv[-1] 1 -done -rm[0]

#@gimp _YCbCr Curves
#@gimp Luminance : gimp_apply_YCbCrcurve, gimp_apply_Ycurve_preview
#@gimp : Starting Y = int(0,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(1) = int(-1,-1,255)
#@gimp : Y-coord(1) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(2) = int(-1,-1,255)
#@gimp : Y-coord(2) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(3) = int(-1,-1,255)
#@gimp : Y-coord(3) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(4) = int(-1,-1,255)
#@gimp : Y-coord(4) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(5) = int(-1,-1,255)
#@gimp : Y-coord(5) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : Ending Y = int(255,0,255)
#@gimp : sep = separator()
#@gimp : Curve smoothness = float(1,0,1)
#@gimp : Display histogram = float(0,0,100)
#@gimp : Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")

#@gimp Blue chrominance : gimp_apply_YCbCrcurve, gimp_apply_Cbcurve_preview
#@gimp : Starting Y = int(0,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(1) = int(-1,-1,255)
#@gimp : Y-coord(1) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(2) = int(-1,-1,255)
#@gimp : Y-coord(2) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(3) = int(-1,-1,255)
#@gimp : Y-coord(3) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(4) = int(-1,-1,255)
#@gimp : Y-coord(4) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(5) = int(-1,-1,255)
#@gimp : Y-coord(5) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : Ending Y = int(255,0,255)
#@gimp : sep = separator()
#@gimp : Curve smoothness = float(1,0,1)
#@gimp : Display histogram = float(0,0,100)
#@gimp : Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")

#@gimp Red Chrominance : gimp_apply_YCbCrcurve, gimp_apply_Crcurve_preview
#@gimp : Starting Y = int(0,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(1) = int(-1,-1,255)
#@gimp : Y-coord(1) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(2) = int(-1,-1,255)
#@gimp : Y-coord(2) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(3) = int(-1,-1,255)
#@gimp : Y-coord(3) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(4) = int(-1,-1,255)
#@gimp : Y-coord(4) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(5) = int(-1,-1,255)
#@gimp : Y-coord(5) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : Ending Y = int(255,0,255)
#@gimp : sep = separator()
#@gimp : Curve smoothness = float(1,0,1)
#@gimp : Display histogram = float(0,0,100)
#@gimp : Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_apply_YCbCrcurve : -skip $1
  -gimp_apply_YCbCrcurve_configfile
  -repeat {@#-1} -l[$>,-1]
    -to_colormode[0] {max(3,s)} -sh[0] 0,2 -rgb2ycbcr[-1] -rm[-1]
    -sh[0] 0,0 -_gimp_apply_YCbCrcurve[-1] @{-2,0-12} -rm[-1]
    -sh[0] 1,1 -_gimp_apply_YCbCrcurve[-1] @{-2,13-25} -rm[-1]
    -sh[0] 2,2 -_gimp_apply_YCbCrcurve[-1] @{-2,26-38} -rm[-1]
    -sh[0] 0,2 -ycbcr2rgb[-1] -rm[-1]
  -endl -done
  -rm[-1]

_gimp_apply_YCbCrcurve :
  -apply_curve $13,0,$1,\
                   @{"-if {$2>=0} -u $2,$3, -else -u \"\" -endif"}\
                   @{"-if {$4>=0} -u $4,$5, -else -u \"\" -endif"}\
                   @{"-if {$6>=0} -u $6,$7, -else -u \"\" -endif"}\
                   @{"-if {$8>=0} -u $8,$9, -else -u \"\" -endif"}\
                   @{"-if {$10>=0} -u $10,$11, -else -u \"\" -endif"}\
                   255,$12
  -c 0,255

gimp_apply_Ycurve_preview :
  -gimp_apply_YCbCrcurve_configfile
  -sh[-1] 0,0,0,0 -f[-1] ${1--3} -rm[-1]
  -gimp_apply_YCbCrcurve_preview[0--2] @-1,0,${-2,-1} -rm[-1]

gimp_apply_Cbcurve_preview :
  -gimp_apply_YCbCrcurve_configfile
  -sh[-1] 1,1,0,0 -f[-1] ${1--3} -rm[-1]
  -gimp_apply_YCbCrcurve_preview[0--2] @-1,1,${-2,-1} -rm[-1]

gimp_apply_Crcurve_preview :
  -gimp_apply_YCbCrcurve_configfile
  -sh[-1] 2,2,0,0 -f[-1] ${1--3} -rm[-1]
  -gimp_apply_YCbCrcurve_preview[0--2] @-1,2,${-2,-1} -rm[-1]

gimp_apply_YCbCrcurve_configfile :
  filename=@{-path_tmp}/.gmic_YCbCrcurve.dlm
  -if $filename $filename -else (0,-1,128,-1,128,-1,128,-1,128,-1,128,255,1) -r[-1] 100%,3 -endif

gimp_apply_YCbCrcurve_preview :
  (${1--3}) -r[-1] 13,3,1,1,-1 -o[-1] @{-path_tmp}/.gmic_YCbCrcurve.dlm -rm[-1]
  -function1d $13,0,$1,\
                  @{"-if {$2>=0} -u $2,$3, -else -u \"\" -endif"}\
                  @{"-if {$4>=0} -u $4,$5, -else -u \"\" -endif"}\
                  @{"-if {$6>=0} -u $6,$7, -else -u \"\" -endif"}\
                  @{"-if {$8>=0} -u $8,$9, -else -u \"\" -endif"}\
                  @{"-if {$10>=0} -u $10,$11, -else -u \"\" -endif"}\
                  255,$12
  -function1d $26,0,$14,\
                  @{"-if {$15>=0} -u $15,$16, -else -u \"\" -endif"}\
                  @{"-if {$17>=0} -u $17,$18, -else -u \"\" -endif"}\
                  @{"-if {$19>=0} -u $19,$20, -else -u \"\" -endif"}\
                  @{"-if {$21>=0} -u $21,$22, -else -u \"\" -endif"}\
                  @{"-if {$23>=0} -u $23,$24, -else -u \"\" -endif"}\
                  255,$25
  -function1d $39,0,$27,\
                  @{"-if {$28>=0} -u $28,$29, -else -u \"\" -endif"}\
                  @{"-if {$30>=0} -u $30,$31, -else -u \"\" -endif"}\
                  @{"-if {$32>=0} -u $32,$33, -else -u \"\" -endif"}\
                  @{"-if {$34>=0} -u $34,$35, -else -u \"\" -endif"}\
                  @{"-if {$36>=0} -u $36,$37, -else -u \"\" -endif"}\
                  255,$38
  -a[-3--1] y -mv[-1] 0
  -repeat {@#-1}
    [-1]
    --gimp_split_preview[-1] "-gimp_apply_YCbCrcurve 0",$-1
    -axes[-1] 0,255,255,0,13,1,255 -grid[-1] 10%,10%,0,0,0.3,0xCCCCCCCC,255
    -line[-1] 0,100%,100%,0,0.3,0xCCCCCCCC,255
     -if $-2
        [-1],[-1],1,1,-{$-2*255/100} -to_gray[-3] -histogram[-3] 256,0,255 -graph[-1] [-3],3,0,0,0,1,0
        -rm[-3] -+[-1] {$-2*255/100} -+[-2,-1] -c[-1] 0,255
     -else -rm[-2] -endif
     -line[-1] 0,100%,100%,0,0.3,0xCCCCCCCC,255
     -sh[0] 0,0,0,0
     -graph[-2] [-1],1,0,255,0,1,255,255,255 --[-1] 1
     -graph[-2] [-1],1,0,255,0,0.5,200,200,200 -rm[-1]
     -sh[0] 1,1,0,0
     -graph[-2] [-1],1,0,255,0,1,128,128,255 --[-1] 1
     -graph[-2] [-1],1,0,255,0,0.5,0,0,200 -rm[-1]
     -sh[0] 2,2,0,0
     -graph[-2] [-1],1,0,255,0,1,255,128,128 --[-1] 1
     -graph[-2] [-1],1,0,255,0,0.5,200,0,0 -rm[-1]
     -if {$40==0}
       -_gimp_apply_curve_preview 0,$1,0 -_gimp_apply_curve_preview $2,$3,1
       -_gimp_apply_curve_preview $4,$5,2 -_gimp_apply_curve_preview $6,$7,3
       -_gimp_apply_curve_preview $8,$9,4 -_gimp_apply_curve_preview $10,$11,5
       -_gimp_apply_curve_preview 255,$12,6
     -elif {$40==1}
       -_gimp_apply_curve_preview 0,$14,0 -_gimp_apply_curve_preview $15,$16,1
       -_gimp_apply_curve_preview $17,$18,2 -_gimp_apply_curve_preview $19,$20,3
       -_gimp_apply_curve_preview $21,$22,4 -_gimp_apply_curve_preview $23,$24,5
       -_gimp_apply_curve_preview 255,$25,6
     -else
       -_gimp_apply_curve_preview 0,$27,0 -_gimp_apply_curve_preview $28,$29,1
       -_gimp_apply_curve_preview $30,$31,2 -_gimp_apply_curve_preview $32,$33,3
       -_gimp_apply_curve_preview $34,$35,4 -_gimp_apply_curve_preview $36,$37,5
       -_gimp_apply_curve_preview 255,$38,6
     -endif
  -mv[-1] 1 -done -rm[0]


#@gimp _Lab Curves
#@gimp Lightness : gimp_apply_Labcurve, gimp_apply_Lcurve_preview
#@gimp : Starting Y = int(0,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(1) = int(-1,-1,255)
#@gimp : Y-coord(1) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(2) = int(-1,-1,255)
#@gimp : Y-coord(2) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(3) = int(-1,-1,255)
#@gimp : Y-coord(3) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(4) = int(-1,-1,255)
#@gimp : Y-coord(4) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(5) = int(-1,-1,255)
#@gimp : Y-coord(5) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : Ending Y = int(255,0,255)
#@gimp : sep = separator()
#@gimp : Curve smoothness = float(1,0,1)
#@gimp : Display histogram = float(0,0,100)
#@gimp : Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")

#@gimp A-color : gimp_apply_Labcurve, gimp_apply_acurve_preview
#@gimp : Starting Y = int(0,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(1) = int(-1,-1,255)
#@gimp : Y-coord(1) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(2) = int(-1,-1,255)
#@gimp : Y-coord(2) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(3) = int(-1,-1,255)
#@gimp : Y-coord(3) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(4) = int(-1,-1,255)
#@gimp : Y-coord(4) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(5) = int(-1,-1,255)
#@gimp : Y-coord(5) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : Ending Y = int(255,0,255)
#@gimp : sep = separator()
#@gimp : Curve smoothness = float(1,0,1)
#@gimp : Display histogram = float(0,0,100)
#@gimp : Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")

#@gimp B-color : gimp_apply_Labcurve, gimp_apply_bcurve_preview
#@gimp : Starting Y = int(0,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(1) = int(-1,-1,255)
#@gimp : Y-coord(1) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(2) = int(-1,-1,255)
#@gimp : Y-coord(2) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(3) = int(-1,-1,255)
#@gimp : Y-coord(3) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(4) = int(-1,-1,255)
#@gimp : Y-coord(4) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(5) = int(-1,-1,255)
#@gimp : Y-coord(5) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : Ending Y = int(255,0,255)
#@gimp : sep = separator()
#@gimp : Curve smoothness = float(1,0,1)
#@gimp : Display histogram = float(0,0,100)
#@gimp : Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_apply_Labcurve : -skip $1
  -gimp_apply_Labcurve_configfile
  -repeat {@#-1} -l[$>,-1]
    -to_colormode[0] {max(3,s)} -sh[0] 0,2 -rgb2lab[-1] -rm[-1]
    -sh[0] 0,0 -*[-1] 2.55 -_gimp_apply_Labcurve[-1] @{-2,0-12} -/[-1] 2.55 -rm[-1]
    -sh[0] 1,1 -+[-1] 86 -*[-1] 1.38587 -_gimp_apply_Labcurve[-1] @{-2,13-25} -/[-1] 1.38587 --[-1] 86 -rm[-1]
    -sh[0] 2,2 -+[-1] 108 -*[-1] 1.25616 -_gimp_apply_Labcurve[-1] @{-2,26-38} -/[-1] 1.25616 --[-1] 108 -rm[-1]
    -sh[0] 0,2 -lab2rgb[-1] -rm[-1]
  -endl -done
  -rm[-1]

_gimp_apply_Labcurve :
  -apply_curve $13,0,$1,\
                   @{"-if {$2>=0} -u $2,$3, -else -u \"\" -endif"}\
                   @{"-if {$4>=0} -u $4,$5, -else -u \"\" -endif"}\
                   @{"-if {$6>=0} -u $6,$7, -else -u \"\" -endif"}\
                   @{"-if {$8>=0} -u $8,$9, -else -u \"\" -endif"}\
                   @{"-if {$10>=0} -u $10,$11, -else -u \"\" -endif"}\
                   255,$12
  -c 0,255

gimp_apply_Lcurve_preview :
  -gimp_apply_Labcurve_configfile
  -sh[-1] 0,0,0,0 -f[-1] ${1--3} -rm[-1]
  -gimp_apply_Labcurve_preview[0--2] @-1,0,${-2,-1} -rm[-1]

gimp_apply_acurve_preview :
  -gimp_apply_Labcurve_configfile
  -sh[-1] 1,1,0,0 -f[-1] ${1--3} -rm[-1]
  -gimp_apply_Labcurve_preview[0--2] @-1,1,${-2,-1} -rm[-1]

gimp_apply_bcurve_preview :
  -gimp_apply_Labcurve_configfile
  -sh[-1] 2,2,0,0 -f[-1] ${1--3} -rm[-1]
  -gimp_apply_Labcurve_preview[0--2] @-1,2,${-2,-1} -rm[-1]

gimp_apply_Labcurve_configfile :
  filename=@{-path_tmp}/.gmic_Labcurve.dlm
  -if $filename $filename -else (0,-1,128,-1,128,-1,128,-1,128,-1,128,255,1) -r[-1] 100%,3 -endif

gimp_apply_Labcurve_preview :
  (${1--3}) -r[-1] 13,3,1,1,-1 -o[-1] @{-path_tmp}/.gmic_Labcurve.dlm -rm[-1]
  -function1d $13,0,$1,\
                  @{"-if {$2>=0} -u $2,$3, -else -u \"\" -endif"}\
                  @{"-if {$4>=0} -u $4,$5, -else -u \"\" -endif"}\
                  @{"-if {$6>=0} -u $6,$7, -else -u \"\" -endif"}\
                  @{"-if {$8>=0} -u $8,$9, -else -u \"\" -endif"}\
                  @{"-if {$10>=0} -u $10,$11, -else -u \"\" -endif"}\
                  255,$12
  -function1d $26,0,$14,\
                  @{"-if {$15>=0} -u $15,$16, -else -u \"\" -endif"}\
                  @{"-if {$17>=0} -u $17,$18, -else -u \"\" -endif"}\
                  @{"-if {$19>=0} -u $19,$20, -else -u \"\" -endif"}\
                  @{"-if {$21>=0} -u $21,$22, -else -u \"\" -endif"}\
                  @{"-if {$23>=0} -u $23,$24, -else -u \"\" -endif"}\
                  255,$25
  -function1d $39,0,$27,\
                  @{"-if {$28>=0} -u $28,$29, -else -u \"\" -endif"}\
                  @{"-if {$30>=0} -u $30,$31, -else -u \"\" -endif"}\
                  @{"-if {$32>=0} -u $32,$33, -else -u \"\" -endif"}\
                  @{"-if {$34>=0} -u $34,$35, -else -u \"\" -endif"}\
                  @{"-if {$36>=0} -u $36,$37, -else -u \"\" -endif"}\
                  255,$38
  -a[-3--1] y -mv[-1] 0
  -repeat {@#-1}
    [-1]
    --gimp_split_preview[-1] "-gimp_apply_Labcurve 0",$-1
    -axes[-1] 0,255,255,0,13,1,255 -grid[-1] 10%,10%,0,0,0.3,0xCCCCCCCC,255
    -line[-1] 0,100%,100%,0,0.3,0xCCCCCCCC,255
     -if $-2
        [-1],[-1],1,1,-{$-2*255/100} -to_gray[-3] -histogram[-3] 256,0,255 -graph[-1] [-3],3,0,0,0,1,0
        -rm[-3] -+[-1] {$-2*255/100} -+[-2,-1] -c[-1] 0,255
     -else -rm[-2] -endif
     -line[-1] 0,100%,100%,0,0.3,0xCCCCCCCC,255
     -sh[0] 0,0,0,0
     -graph[-2] [-1],1,0,255,0,1,255,255,255 --[-1] 1
     -graph[-2] [-1],1,0,255,0,0.5,200,200,200 -rm[-1]
     -sh[0] 1,1,0,0
     -graph[-2] [-1],1,0,255,0,1,255,128,128 --[-1] 1
     -graph[-2] [-1],1,0,255,0,0.5,200,0,0 -rm[-1]
     -sh[0] 2,2,0,0
     -graph[-2] [-1],1,0,255,0,1,128,128,255 --[-1] 1
     -graph[-2] [-1],1,0,255,0,0.5,0,0,200 -rm[-1]
     -if {$40==0}
       -_gimp_apply_curve_preview 0,$1,0 -_gimp_apply_curve_preview $2,$3,1
       -_gimp_apply_curve_preview $4,$5,2 -_gimp_apply_curve_preview $6,$7,3
       -_gimp_apply_curve_preview $8,$9,4 -_gimp_apply_curve_preview $10,$11,5
       -_gimp_apply_curve_preview 255,$12,6
     -elif {$40==1}
       -_gimp_apply_curve_preview 0,$14,0 -_gimp_apply_curve_preview $15,$16,1
       -_gimp_apply_curve_preview $17,$18,2 -_gimp_apply_curve_preview $19,$20,3
       -_gimp_apply_curve_preview $21,$22,4 -_gimp_apply_curve_preview $23,$24,5
       -_gimp_apply_curve_preview 255,$25,6
     -else
       -_gimp_apply_curve_preview 0,$27,0 -_gimp_apply_curve_preview $28,$29,1
       -_gimp_apply_curve_preview $30,$31,2 -_gimp_apply_curve_preview $32,$33,3
       -_gimp_apply_curve_preview $34,$35,4 -_gimp_apply_curve_preview $36,$37,5
       -_gimp_apply_curve_preview 255,$38,6
     -endif
  -mv[-1] 1 -done -rm[0]

#@gimp _Black &amp; White : gimp_blackandwhite, gimp_blackandwhite_preview(1)
#@gimp : Red level = float(0.299,0,1)
#@gimp : Red smoothness = float(0,0,10)
#@gimp : Green level = float(0.587,0,1)
#@gimp : Green smoothness = float(0,0,10)
#@gimp : Blue level = float(0.114,0,1)
#@gimp : Blue smoothness = float(0,0,10)
#@gimp : sep = separator()
#@gimp : Gamma = float(1,0.01,5)
#@gimp : Contrast = float(1,0,4)
#@gimp : Brightness = float(0,-255,255)
#@gimp : Hue = float(0,0,360)
#@gimp : Saturation = float(0,0,1)
#@gimp : sep = separator()
#@gimp : Grain (shadows) = float(0,0,200)
#@gimp : Grain (midtones) = float(0,0,200)
#@gimp : Grain (highlights) = float(0,0,200)
#@gimp : Grain tone fading = float(2,0,10)
#@gimp : Grain scale = float(0,0,3)
#@gimp : Grain type = choice("Gaussian","Uniform","Salt and pepper","Poisson")
#@gimp : sep = separator()
#@gimp : Local contrast = float(0,0,60)
#@gimp : Radius = int(16,1,512)
#@gimp : Contrast smoothness = float(4,0,10)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_blackandwhite :
  -repeat @#
    -l[-1] -split_opacity -rv -to_rgb[-1] -s[-1] c          # Isolate opacity
    -*[-3] $1 -b[-3] $2%                                    # Red contrast + smoothness
    -*[-2] $3 -b[-2] $4%                                    # Green contrast + smoothness
    -*[-1] $5 -b[-1] $6%                                    # Blue contrast + smoothness
    -+[-3--1] -/[-1] {$1+$3+$5} -c[-1] 0,255                # (R,G,B) -> B&W

    -apply_gamma[-1] $7                                     # Gamma correction
    --[-1] 128 -*[-1] $8 -+[-1] 128 -+[-1] $9 -c[-1] 0,255  # B&W contrast and brightness.

    100%,100% [-1]x2                                        # Create noise for shadows, midtones and highlights.
    -noise[-3] 100,$17 -b[-3] $16% -n[-3] -$12,$12          # Scaled grain on shadows.
    -noise[-2] 100,$17 -b[-2] $16% -n[-2] -$13,$13          # Scaled grain on midtones.
    -noise[-1] 100,$17 -b[-1] $16% -n[-1] -$14,$14          # Scaled grain on highlights.

    --tones[-4] 3 -b[-3--1] $15%                            # Get smoothed tones.
    -*[-6,-3] -*[-4,-2] -*[-2,-1]                           # Get noisy tones.
    -+[-4--1] -c[-1] 0,255                                  # Compose them with the B&W image.

    -if {$10||$11}
      -/[-1] 255
      -i[-2] 100%,100%,1,1,$11
      -i[-3] 100%,100%,1,1,$10
      -a[-3--1] c -hsv2rgb[-1]
    -endif

    -rv -a c -endl -mv[-1] 0 -done                          # Re-compose opacity and loop to next image.
  -normalize_local $18,$19,$20,2%,1,0,255

gimp_blackandwhite_preview :
  -gimp_split_preview "-gimp_blackandwhite ${1--2}",$-1

#@gimp Sepia : gimp_sepia, gimp_sepia_preview
#@gimp : Gamma = float(1,0.01,5)
#@gimp : Contrast = float(1,0,4)
#@gimp : Brightness = float(0,-255,255)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_sepia :
  -sepia
  -repeat @#
    -sh[-1] 0,2
    -apply_gamma[-1] $1 --[-1] 128 -*[-1] $2 -+[-1] {128+$3} -c[-1] 0,255
  -rm[-1] -mv[-1] 0 -done

gimp_sepia_preview :
  -gimp_split_preview "-gimp_sepia ${1--2}",$-1

#@gimp Abstraction : gimp_color_abstraction, gimp_color_abstraction_preview(0)
#@gimp : Smoothness = float(1,0,10)
#@gimp : Levels = int(10,2,255)
#@gimp : Contrast = float(0.2,0.01,1)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2011/10/19</i>.</small>")
gimp_color_abstraction :
  -to_rgb -b $1 -quantize $2 -area 0 -^ $3 -n 0,255

gimp_color_abstraction_preview :
  -gimp_split_preview "-gimp_color_abstraction ${1--2}",$-1

#@gimp Colormap : gimp_colormap,gimp_colormap_preview
#@gimp : Colormap = choice[1,"Adaptive","Custom","Standard (256)","HSV (256)","Lines (256)","Hot (256)","Cool (256)","Jet (256)","Flag (256)","Cube (256)"]
#@gimp : Dithering = float(1,0,1)
#@gimp : sep = separator(), note = note("<small><i>For adaptive and custom colormaps only :</i></small>")
#@gimp : Number of tones = int(32,2,256)
#@gimp : sep = separator(), note = note("<small><i>For custom colormaps only :</i></small>")
#@gimp : Number of colors = int(8,2,8)
#@gimp : 1st color = color(0,0,0)
#@gimp : 2nd color = color(255,255,255)
#@gimp : 3rd color = color(255,0,0)
#@gimp : 4th color = color(0,255,0)
#@gimp : 5th color = color(0,0,255)
#@gimp : 6th color = color(255,255,0)
#@gimp : 7th color = color(255,0,255)
#@gimp : 8th color = color(0,255,255)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2011/12/27</i>.</small>")
gimp_colormap :
  -repeat @# -l[$>] -split_opacity -to_rgb[0]
    -if {$1>=2}                # Pre-defined colormap.
      -index[0] {$1-2},$2,1
    -elif {$1==1}              # Custom colormap.
      (${5-28}) -z[-1] 0,{3*$4-1}
      -r[-1] 3,{w/3},1,1,-1 -permute[-1] yzcx -r[-1] $3,1,1,3,3
      -index[0] [-1],$2,1 -rm[-1]
    -else                      # Adaptive colormap.
      -autoindex[0] $3,$2,{if($3<=32,1,0)}
    -endif
    -a c
  -endl -done

gimp_colormap_preview :
  -gimp_split_preview "-gimp_colormap ${1--2}",$-1

#@gimp B&amp;W recolorize : gimp_bwrecolorize, gimp_bwrecolorize_preview
#@gimp : Gamma = float(1,0.01,5)
#@gimp : Contrast = float(1,0,4)
#@gimp : Brightness = float(0,-255,255)
#@gimp : Normalize = bool(0)
#@gimp : sep = separator()
#@gimp : Gradient preset = choice("User-defined","Black to white","White to black","Sepia","Solarize")
#@gimp : Interpolation type = choice(1,"Nearest","Linear","Cubic","Lanczos")
#@gimp : Preserve initial brightness = bool(0)
#@gimp : sep = separator(), note = note("<small><u>User-defined gradient :</u></small>")
#@gimp : Number of tones = int(5,2,8)
#@gimp : 1st tone = color(0,0,0,255)
#@gimp : 2nd tone = color(43,25,55,255)
#@gimp : 3rd tone = color(158,137,189,255)
#@gimp : 4th tone = color(224,191,228,255)
#@gimp : 5th tone = color(255,255,255,255)
#@gimp : 6th tone = color(255,255,255,255)
#@gimp : 7th tone = color(255,255,255,255)
#@gimp : 8th tone = color(255,255,255,255)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_bwrecolorize :
  -if $4 -n 0,255 -endif
  -if {$5==0}  # User-defined gradient
    -to_rgba (${9--2}) -r[-1] 4,$8,1,1,-1 -permute[-1] yzcx
  -elif {$5==1} # Black to white
    (0,255^0,255^0,255^255,255)
  -elif {$5==2} # White to black
    (255,0^255,0^255,0^255,255)
  -elif {$5==3} # Sepia
    (0,44,115,143,196,244^0,20,84,119,184,235^0,5,44,73,144,200^255,255,255,255,255,255)
  -else         # Solarize
    (0,359^1,1^1,1^255,255) -r[-1] 256,1,1,4,3 -sh[-1] 0,2 -hsv2rgb[-1] -rm[-1]
  -endif
  -if {$6==0} -r[-1] 256,1,1,4,1
  -elif {$6==1} -r[-1] 256,1,1,4,3
  -elif {$6==2} -r[-1] 256,1,1,4,5 -c[-1] 0,255
  -else -r[-1] 256,1,1,4,6
  -endif
  -if {$7==1} -sh[-1] 0,2 -rgb2hsv[-1] -sh[-1] 2,2 -f[-1] x/w -hsv2rgb[-2] -rm[-2,-1] -endif
  -repeat {@#-1}
    s=@{$>,s}
    -luminance[$>] -apply_gamma[$>] $1 --[$>] 128 -*[$>] $2 -+[$>] {$3+128} -c[$>] 0,255
    -map[$>] [-1] -to_colormode[$>] $s
  -done
  -rm[-1]

gimp_bwrecolorize_preview :
  -gimp_split_preview "-gimp_bwrecolorize ${^0}",$-1

#@gimp B&amp;W dithering : gimp_ditheredbw, gimp_ditheredbw_preview(0)
#@gimp : Gamma = float(1,0.01,5)
#@gimp : Contrast = float(1,0,4)
#@gimp : Brightness = float(0,-255,255)
#@gimp : Smoothness = float(0,0,10)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_ditheredbw :
  -apply_gamma[-1] $1 -- 128 -* $2 -+ 128 -+ $3 -b $4 -c 0,255 -ditheredbw

gimp_ditheredbw_preview :
  -gimp_split_preview "-gimp_ditheredbw ${1--2}",$-1

#@gimp Tone mapping : gimp_map_tones, gimp_map_tones_preview(0)
#@gimp : Threshold = float(0.5,0,1)
#@gimp : Gamma = float(0.7,0,1)
#@gimp : Smoothness = float(0.1,0,10)
#@gimp : Iterations = int(30,0,500)
#@gimp : Channel(s) = choice(3,"All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_map_tones :
  -apply_channels "-map_tones ${1-4}",$5,0
  -n 0,255

gimp_map_tones_preview :
  -gimp_split_preview "-gimp_map_tones ${1--2}",$-1

#@gimp Fast tone mapping : gimp_map_tones_fast, gimp_map_tones_fast_preview(0)
#@gimp : Radius = float(3,0,20)
#@gimp : Power = float(0.5,0,1)
#@gimp : Channel(s) = choice(3,"All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Authors : <i>Paul Nasca, David Tschumperl&#233;</i>.      Latest update : <i>2011/06/10</i>.</small>")
gimp_map_tones_fast :
  -apply_channels "-map_tones_fast $1,$2",$3,0

gimp_map_tones_fast_preview :
  -gimp_split_preview "-gimp_map_tones_fast ${^0}",$-1

#@gimp Local normalization : gimp_normalize_local, gimp_normalize_local_preview(0)
#@gimp : Amplitude = float(2,0,60)
#@gimp : Radius = int(6,1,64)
#@gimp : Neighborhood smoothness = float(5,0,40)
#@gimp : Average smoothness = float(20,0,40)
#@gimp : Constrain values = bool(1)
#@gimp : Channel(s) = choice(3,"All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_normalize_local :
  -apply_channels "-normalize_local $1,$2,$3,$4,$5,0,255",$6,0

gimp_normalize_local_preview :
  -gimp_split_preview "-gimp_normalize_local ${1--2}",$-1

#@gimp Select color : gimp_select_color, gimp_select_color(1)
#@gimp : Similarity space = choice(0,"RGB[A]","RGB","YCbCr","Red","Green","Blue","Opacity","Luminance","Blue & Red chrominances","Hue","Saturation")
#@gimp : Tolerance = float(20,0,100)
#@gimp : Smoothness = float(0,0,10)
#@gimp : Selected color = color(255,255,255,255)
#@gimp : Output as = choice(0,"Selected colors","Selected mask")
#@gimp : Invert selection = bool(0)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
_gimp_select_color :
  -if {$1==1} -to_rgb                            # RGB
  -elif {$1==2} -to_rgb -rgb2ycbcr               # YCbCr
  -elif {$1==3} -channels 0                      # R
  -elif {$1==4} -channels 1                      # G
  -elif {$1==5} -channels 2                      # B
  -elif {$1==6} -to_rgba -channels 3             # Opacity
  -elif {$1==7} -to_rgb -rgb2ycbcr -channels 0   # Luminance
  -elif {$1==8} -to_rgb -rgb2ycbcr -channels 1,2 # B&R chrominances
  -elif {$1==9} -to_rgb -rgb2hsv -channels 0     # Hue
  -elif {$1==10} -to_rgb -rgb2hsv -channels 1    # Saturation
  -endif

gimp_select_color :
  ($4^$5^$6^$7) -_gimp_select_color[-1] $1 color=@-1 -rm[-1]
  -repeat @#
    -if {$8==0}                                  # Output selected colors.
      --_gimp_select_color[-1] $1
      -select_color[-1] $2%,$color
      -b[-1] $3%
      -if $9 -*[-1] -1 -+[-1] 1 -endif
      -to_rgba[-2] -s[-2] c -*[-2,-1] -a[-4--1] c
    -else
      -_gimp_select_color[-1] $1
      -select_color[-1] $2%,$color
      -b[-1] $3
      -if $9 -*[-1] -1 -+[-1] 1 -endif
      -*[-1] 255 -r[-1] 100%,100%,1,4
    -endif
  -mv[-1] 0 -done

#@gimp Replace color : gimp_replace_color, gimp_replace_color(0)
#@gimp : Tolerance = float(100,1,450)
#@gimp : Smoothness = float(0,0,10)
#@gimp : Selected color = color(255,255,255,255)
#@gimp : Replaced color = color(0,0,0,0)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_replace_color :
  -to_rgba -replace_color $1,$2%,${3--1} -c 0,255

#@gimp User-defined : gimp_custom_transform, gimp_custom_transform
#@gimp : Red - Green - Blue - Alpha = text{"i"}
#@gimp : Red - Green - Blue = text{"i + 90*(x/w)*cos(i/10)"}
#@gimp : Red = text{"i"}
#@gimp : Green = text{"i"}
#@gimp : Blue = text{"i"}
#@gimp : Alpha = text{"i"}
#@gimp : Value normalization = choice("None","RGB","RGBA")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_custom_transform :
  -to_rgba -repeat @#
    -f[-1] "$1"
    -s[-1] c -a[-4--2] c -f[-2] "$2"
    -s[-2] c -f[-4] "$3" -f[-3] "$4" -f[-2] "$5" -f[-1] "$6"
    -if {$7==0} -a[-4--1] c -c[-1] 0,255
    -elif {$7==1} -a[-4--2] c -n[-2] 0,255 -c[-1] 0,255 -a[-2,-1] c
    -else -a[-4--1] c -n[-1] 0,255
    -endif
  -mv[-1] 0 -done

#@gimp Linear gradient : gimp_linear_gradient, gimp_linear_gradient
#@gimp : Starting color = color(0,0,0,255)
#@gimp : Ending color = color(255,255,255,255)
#@gimp : Swap colors = bool(0)
#@gimp : Angle = float(45,0,360)
#@gimp : Fade start = float(0,0,100)
#@gimp : Fade end = float(100,0,100)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_linear_gradient :
  -repeat @#
    ({w},{h}) -rm[-2]
    ($1^$2^$3^$4) ($5^$6^$7^$8)
    -if $9 -rv[-2,-1] -endif
    -r[-2,-1] @-3 -rm[-3]
    -fade_linear $10,$11,$12
  -mv[-1] 0 -done

#@gimp Radial gradient : gimp_radial_gradient, gimp_radial_gradient
#@gimp : Starting color = color(0,0,0,255)
#@gimp : Ending color = color(255,255,255,255)
#@gimp : Swap colors = bool(0)
#@gimp : Fade start = float(0,0,100)
#@gimp : Fade end = float(100,0,100)
#@gimp : X-center = float(50,0,100)
#@gimp : Y-center = float(50,0,100)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_radial_gradient :
  -repeat @#
    ({w},{h}) -rm[-2]
    ($1^$2^$3^$4) ($5^$6^$7^$8)
    -if $9 -rv[-2,-1] -endif
    -r[-2,-1] @-3 -rm[-3]
    100%,100% -=[-1] 1,$12%,$13% -distance[-1] 1 -_fade $10,$11
  -mv[-1] 0 -done

#@gimp Corner gradient : gimp_corner_gradient, gimp_corner_gradient
#@gimp : Color 1 (up/left corner) = color(255,255,255,128)
#@gimp : Color 2 (up/right corner) = color(255,0,0,255)
#@gimp : Color 3 (bottom/left corner) = color(0,255,0,255)
#@gimp : Color 4 (bottom/right corner) = color(0,0,255,255)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_corner_gradient :
  -repeat @#
    ({w},{h}) -rm[-2]
    ($1,$5;$9,$13^$2,$6;$10,$14^$3,$7;$11,$15^$4,$8;$12,$16) -r[-1] @-2,1,4,3 -rm[-2]
  -mv[-1] 0 -done


#@gimp _<b>Contours</b>
#----------------------

#@gimp Curvature : gimp_curvature, gimp_curvature_preview(0)
#@gimp : Smoothness = float(2,0,10)
#@gimp : Min threshold = float(0,0,100)
#@gimp : Max threshold = float(100,0,100)
#@gimp : Absolute value = bool(0)
#@gimp : Negative colors = bool(0)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_curvature :
  -b $1 -iee
  -if $4 -abs -endif
  -c $2%,$3%
  -if $5 -negative -endif
  -n 0,255

gimp_curvature_preview :
  -gimp_split_preview "-gimp_curvature ${^0}",$-1

#@gimp Difference of gaussians : gimp_dog, gimp_dog_preview(1)
#@gimp : 1st Variance = float(1.4,0,5)
#@gimp : 2nd Variance = float(1.5,0,5)
#@gimp : Threshold = float(0,0,49)
#@gimp : Negative colors = bool(0)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_dog :
  -dog $1%,$2%
  -c $3%,{100-$3}%
  -if $4 -negative -endif
  -n 0,255

gimp_dog_preview :
  -gimp_split_preview "-gimp_dog ${^0}",$-1

#@gimp Distance transform : gimp_distance, gimp_distance_preview(0)
#@gimp : Value = int(128,0,255)
#@gimp : Metric = choice(2,"Chebyshev","Manhattan","Euclidean","Squared-Euclidean")
#@gimp : Normalization = choice(2,"Cut","Normalize","Modulo")
#@gimp : Modulo value = int(32,1,255)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2011/04/07</i>.</small>")
gimp_distance :
  -distance $1,$2
  -if {$3==0} -c 0,255
  -elif {$3==1} -n 0,255
  -else -% $4 -n 0,255
  -endif

gimp_distance_preview :
  -gimp_split_preview "-gimp_distance ${^0}",$-1

#@gimp Edges : gimp_edges, gimp_edges_preview(0)
#@gimp : Smoothness = float(0,0,10)
#@gimp : Threshold = float(15,0,50)
#@gimp : Negative colors = bool(0)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_edges :
  -to_rgb -b $1% -edges $2%
  -if $3 -negative -endif
  -n 0,255

gimp_edges_preview :
  -gimp_split_preview "-gimp_edges ${^0}",$-1

#@gimp Edges offsets : gimp_edge_offsets, gimp_edge_offsets_preview(0)
#@gimp : Smoothness = float(0,0,10)
#@gimp : Threshold = float(15,0,50)
#@gimp : Scale = int(4,0,32)
#@gimp : Thickness = int(1,0,16)
#@gimp : Negative colors = bool(0)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_edge_offsets :
  -repeat @#
    os={s}
    -b[-1] $1% -gradient_norm[-1] -t[-1] $2% -skeleton[-1] 0 -distance[-1] 1 -round[-1] 1 -%[-1] $3 -t[-1] {max(1,$3-$4)}
    -if {!$5} -negative[-1] -endif
    -n[-1] 0,255 -to_colormode[-1] $os
  -mv[-1] 0 -done

gimp_edge_offsets_preview :
  -gimp_split_preview "-gimp_edge_offsets ${^0}",$-1

#@gimp Laplacian : gimp_laplacian, gimp_laplacian_preview(0)
#@gimp : Smoothness = float(0,0,10)
#@gimp : Min threshold = float(0,0,100)
#@gimp : Max threshold = float(100,0,100)
#@gimp : Absolute value = bool(0)
#@gimp : Negative colors = bool(0)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_laplacian :
  -b $1 -laplacian
  -if $4 -abs -endif
  -c $2%,$3%
  -if $5 -negative -endif
  -n 0,255

gimp_laplacian_preview :
  -gimp_split_preview "-gimp_laplacian ${^0}",$-1

#@gimp Local orientation : gimp_local_orientation, gimp_local_orientation_preview(1)
#@gimp : Smoothness = float(0,0,5)
#@gimp : Min threshold = float(0,0,100)
#@gimp : Max threshold = float(100,0,100)
#@gimp : Negative colors = bool(0)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
_gimp_local_orientation :
  -b $1% -gradient_orientation 2 -complex2polar -rm[0--1:2]
  -c $2%,$3%
  -if $4 -negative -endif

gimp_local_orientation :
  -apply_channels "-_gimp_local_orientation $1,$2,$3,$4",$5,1

gimp_local_orientation_preview :
  -gimp_split_preview "-gimp_local_orientation ${^0}",$-1

#@gimp Gradient norm : gimp_gradient_norm, gimp_gradient_norm_preview(0)
#@gimp : Smoothness = float(0,0,10)
#@gimp : Linearity = float(0.5,0,1.5)
#@gimp : Min threshold = float(0,0,100)
#@gimp : Max threshold = float(100,0,100)
#@gimp : Negative colors = bool(0)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_gradient_norm :
  -b $1 -gradient_norm -^ $2
  -c $3%,$4%
  -if $5 -negative -endif
  -n 0,255

gimp_gradient_norm_preview :
  -gimp_split_preview "-gimp_gradient_norm ${^0}",$-1

#@gimp Gradient RGB : gimp_gradient2rgb, gimp_gradient2rgb_preview(0)
#@gimp : Smoothness = float(0,0,10)
#@gimp : Min threshold = float(0,0,100)
#@gimp : Max threshold = float(100,0,100)
#@gimp : Orientation only = bool(0)
#@gimp : Negative colors = bool(0)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_gradient2rgb :
  -b $1 -gradient2rgb $4
  -c $2%,$3%
  -if $5 -negative -endif
  -n 0,255

gimp_gradient2rgb_preview :
  -gimp_split_preview "-gimp_gradient2rgb ${^0}",$-1

#@gimp Isophotes : gimp_isophotes, gimp_isophotes_preview(0)
#@gimp : Levels = int(16,1,256)
#@gimp : Smoothness = float(0,0,5)
#@gimp : Filling = choice(0,"Transparent","Colors")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_isophotes :
  -if $3
    -topographic_map $1,$2
  -else
    -b $2 -isophotes $1
  -endif

gimp_isophotes_preview :
  -gimp_split_preview "-gimp_isophotes ${^0}",$-1

#@gimp Morphological filter : gimp_morpho, gimp_morpho_preview(0)
#@gimp : Action = choice("Erosion","Dilation","Opening","Closing",
#@gimp : "Original - Erosion","Dilation - Original","Original - Opening","Closing - Original")
#@gimp : Size = int(5,2,60)
#@gimp : Invert colors = bool(false)
#@gimp : Shape = choice(0,"Square","Octagonal","Circular")
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : Scale = bool(true)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_morpho :
  -apply_channels "-__gimp_morpho ${^0}",$5,$6

gimp_morpho_preview :
  -gimp_split_preview "-gimp_morpho ${^0}",$-1

__gimp_morpho :
  -if {$4==1} suf="_oct" -elif {$4==0} suf="" -else suf="_circ" -endif
  -if {$1==0} -erode$suf $2
  -elif {$1==1} -dilate$suf $2
  -elif {$1==2} -erode$suf $2 -dilate$suf $2
  -elif {$1==3} -dilate$suf $2 -erode$suf $2
  -elif {$1==4} -repeat @# --erode$suf $2 --[-2,-1] -mv[-1] 0 -done
  -elif {$1==5} -repeat @# --dilate$suf $2 -rv[-2,-1] --[-2,-1] -mv[-1] 0 -done
  -elif {$1==6} -repeat @# --erode$suf $2 -dilate$suf[-1] $2 --[-2,-1] -mv[-1] 0 -done
  -else -repeat @# --dilate$suf $2 -erode$suf[-1] $2 -rv[-2,-1] --[-2,-1] -mv[-1] 0 -done
  -endif
  -if $3 -repeat @# -l[$>] -split_opacity -negative[0] -a c -endl -done -endif

#@gimp Segmentation : gimp_segment_watershed, gimp_segment_watershed_preview(0)
#@gimp : Edge threshold = float(2,0,15)
#@gimp : Smoothness = float(1,0,5)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_segment_watershed :
  -apply_channels "-b $2 -segment_watershed $1",$3,0

gimp_segment_watershed_preview :
  -gimp_split_preview "-gimp_segment_watershed ${^0}",$-1

#@gimp Skeleton : gimp_skeleton, gimp_skeleton_preview(1)
#@gimp : Method = choice("Distance","Thinning")
#@gimp : Smoothness = float(0,0,10)
#@gimp : Curviness = float(0,0,10)
#@gimp : Multiple channels = bool(1)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2011/04/07</i>.</small>")
gimp_skeleton :
  -if {!$4} -norm -endif
  -b $2%
  -if $1 -thinning -else -skeleton $3% -endif
  -* 255

gimp_skeleton_preview :
  -gimp_split_preview "-gimp_skeleton ${^0}",$-1

#@gimp Thin edges : gimp_thin_edges, gimp_thin_edges_preview(0)
#@gimp : Smoothness = float(0,0,10)
#@gimp : Threshold = float(15,0,50)
#@gimp : Negative colors = bool(0)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_thin_edges :
  -b $1% -gradient_norm -t $2% -thinning
  -if {!$3} -negative -endif
  -n 0,255

gimp_thin_edges_preview :
  -gimp_split_preview "-gimp_thin_edges ${^0}",$-1


#@gimp _<b>Deformations</b>
#--------------------------


#@gimp Cartesian transform : gimp_custom_deformation, gimp_custom_deformation(1)
#@gimp : X-warping = text{"(w+h)/20 * cos(y*20/h)"}
#@gimp : Y-warping = text{"(w+h)/20 * sin(x*20/w)"}
#@gimp : Relative warping = bool(1)
#@gimp : Interpolation = choice(1,"Nearest neighbor","Linear")
#@gimp : Borders = choice(1,"Black","Nearest","Repeat")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_custom_deformation :
   -repeat @#
    --norm[-1] [-1] -f[-2] "$1" -f[-1] "$2"
    -a[-2,-1] c -warp[-2] [-1],$3,$4,$5,1 -rm[-1]
  -mv[-1] 0 -done

#@gimp Euclidean - Polar : gimp_euclidean2polar, gimp_euclidean2polar(1)
#@gimp : X-center = float(0.5,0,1)
#@gimp : Y-center = float(0.5,0,1)
#@gimp : Dilation = float(1,0.1,10)
#@gimp : Borders = choice(1,"Black","Nearest","Repeat")
#@gimp : Inverse transform = bool(0)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_euclidean2polar :
  -if $5 -polar2euclidean $1,$2,$3,$4 -else -euclidean2polar $1,$2,$3,$4 -endif

#@gimp Fish-eye : fisheye, fisheye(1)
#@gimp : X-center = float(50,0,100)
#@gimp : Y-center = float(50,0,100)
#@gimp : Radius = float(70,0,100)
#@gimp : Amplitude = float(1,0,2)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")

#@gimp Flower : gimp_flower, gimp_flower(1)
#@gimp : Amplitude = float(30,-100,100)
#@gimp : Petals = int(6,0,20)
#@gimp : Offset = float(0,0,100)
#@gimp : Angle = float(0,0,360)
#@gimp : X-center = float(0.5,0,1)
#@gimp : Y-center = float(0.5,0,1)
#@gimp : Borders = choice(1,"Black","Nearest","Repeat")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_flower :
  -flower $1,$2,$3%,$4,$5,$6,$7

#@gimp Perspective : gimp_warp_perspective, gimp_warp_perspective(1)
#@gimp : X-angle = float(1.73,-4,4)
#@gimp : Y-angle = float(0,-4,4)
#@gimp : Zoom = float(1,0.1,4)
#@gimp : X-center = float(50,0,100)
#@gimp : Y-center = float(50,0,100)
#@gimp : X-offset = float(0,0,100)
#@gimp : Y-offset = float(0,0,100)
#@gimp : Borders = choice(2,"Black","Nearest","Repeat")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_warp_perspective :
  -shift $6%,$7%,0,0,2 -warp_perspective $1,$2,$3,$4,$5,$8

#@gimp Random : deform, deform(0)
#@gimp : Amplitude = float(10,0,100)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")

#@gimp Ripple : ripple, ripple(0)
#@gimp : Amplitude = float(10,0,100)
#@gimp : Size = float(20,1,300)
#@gimp : Shape = choice(2,"Bloc","Triangle","Sine","Sine+","Random")
#@gimp : Angle = float(0,0,360)
#@gimp : Offset = float(0,0,500)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2011/08/23</i>.</small>")

#@gimp Sphere : gimp_map_sphere, gimp_map_sphere_preview(1)
#@gimp : Width = _int(512,1,4096)
#@gimp : Height = _int(512,1,4096)
#@gimp : Radius = float(90,0,400)
#@gimp : Dilation = float(0.5,0,1)
#@gimp : Angle = float(0,-50,50)
#@gimp : Border smoothness = float(0,0,200)
#@gimp : Border width = float(20,0,100)
#@gimp : Orientation = choice("0 deg.","90 deg.","180 deg.","270 deg.")
#@gimp : Background = choice("Transparent","Mean color")
#@gimp : Fading = float(0,0,100)
#@gimp : Fading shape = float(0.5,0,3)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2011/11/07</i>.</small>")
gimp_map_sphere :
  -rotate {$8*90}
  -if $6
    -repeat @#
      -shift[-1] 50%,0,0,0,2 --columns[-1] {(1-$7/100)*w/2},{(1+$7/100)*w/2}
      100% -gaussian[-1] {0.1*w},{h},0 100% 100% -a[-3--1] c -r[-1] [-2],[-2],1,3
      -smooth[-2] [-1],$6,5,0 -rm[-1]
      -j[-2] [-1],{(1-$7/100)*@{-2,w}/2} -rm[-1] -shift[-1] -50%,0,0,0,2
    -mv[-1] 0 -done
  -endif
  -shift $5%,0,0,0,2 -to_rgba
  -if $9
    -repeat @#
      --lines[$>] 0 -r[-1] 1,1,1,4,2 RGBA$>=@-1
      -r[-1] [$>],[$>],1,4 --[$>,-1]
    -done
  -endif
  -map_sphere $1,$2,$3,$4,$10,$11
  -if $9
    -repeat @#
      (${RGBA$>}) -y[-1] c -r[-1] [$>],[$>],1,4 -+[$>,-1]
    -done
  -endif

gimp_map_sphere_preview :
  -gimp_map_sphere {w},{h},${3--1}

#@gimp Polar transform : gimp_transform_polar, gimp_transform_polar(1)
#@gimp : Preset = choice("Custom transform","Inverse radius","Swap radius/angle")
#@gimp : X-center = float(50,0,100)
#@gimp : Y-center = float(50,0,100)
#@gimp : Radius = text{"r + R/10*cos(a*5)"}
#@gimp : Angle = text{"a"}
#@gimp : Borders = choice(1,"Black","Nearest","Repeat")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_transform_polar :
  -if {$1==0}
    -transform_polar "$4","$5",$2,$3,$6
  -elif {$1==1}
    -transform_polar R-r,a,$2,$3,$6
  -else
    -transform_polar a*R/(2*pi),r*2*pi/R,$2,$3,$6
  -endif

#@gimp Twirl : twirl, twirl(1)
#@gimp : Amplitude = float(1,-5,5)
#@gimp : X-center = float(0.5,0,1)
#@gimp : Y-center = float(0.5,0,1)
#@gimp : Borders = choice(1,"Black","Nearest","Repeat")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")

#@gimp Water : water, water(0)
#@gimp : Amplitude = float(30,0,300)
#@gimp : Smoothness = float(1.5,0,4)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")

#@gimp Wave : wave, wave(1)
#@gimp : Amplitude = float(10,0,30)
#@gimp : Frequency = float(0.4,0,2)
#@gimp : X-center = float(50,0,100)
#@gimp : Y-center = float(50,0,100)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")

#@gimp Wind : gimp_wind, gimp_wind_preview(0)
#@gimp : Amplitude = int(20,0,500)
#@gimp : Angle = float(0,0,360)
#@gimp : Attenuation = float(0.7,0,1)
#@gimp : Threshold = float(20,0,100)
#@gimp : Mode = choice(1,"Darker","Brighter")
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2011/07/13</i>.</small>")
gimp_wind :
  -if {!$5} -negative -endif
  -apply_channels "-wind ${1-4}",$-2
  -if {!$5} -negative -endif

gimp_wind_preview :
  -gimp_split_preview "-gimp_wind ${1--2}",$-1

#@gimp Zoom : gimp_zoom, gimp_zoom(1)
#@gimp : Factor = float(2,0.01,10)
#@gimp : X-center = float(0.5,0,1)
#@gimp : Y-center = float(0.5,0,1)
#@gimp : Borders = choice(0,"Black","Nearest","Repeat")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_zoom :
  -if {$1<1} -to_rgba -endif
  -zoom $1,$2,$3,0,$4


#@gimp _<b>Degradations</b>
#---------------------------


#@gimp Additive noise : gimp_noise, gimp_noise_preview(0)
#@gimp : Amplitude = float(10,0,200)
#@gimp : Noise type = choice("Gaussian","Uniform","Salt and pepper","Poisson")
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : Value range = choice("Cut","Normalize")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_noise :
  -apply_channels "-noise $1,$2",$3,$4

gimp_noise_preview :
  -gimp_split_preview "-gimp_noise ${1--2}",$-1

#@gimp Angular blur : gimp_blur_angular, gimp_blur_angular(1)
#@gimp : Amplitude = float(2,0,10)
#@gimp : X-center = float(0.5,0,1)
#@gimp : Y-center = float(0.5,0,1)
#@gimp : Sharpness = float(0,0,500)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : Value range = choice("Cut","Normalize")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_blur_angular :
  -apply_channels "-blur_angular $1%,$2,$3 -sharpen $4",$5,$6

#@gimp Bandpass filter : gimp_bandpass, gimp_bandpass_preview(0)
#@gimp : Low frequency = float(0,0,100)
#@gimp : High frequency = float(100,0,100)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : Value range = choice(1,"Cut","Normalize")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_bandpass :
  -apply_channels "-bandpass $1%,$2%",$3,$4

gimp_bandpass_preview :
  -gimp_split_preview "-gimp_bandpass ${1--2}",$-1

#@gimp Bayer filter : rgb2bayer, rgb2bayer(0)
#@gimp : Starting pattern = choice(0,"Red-Green","Blue-Green","Green-Red","Green-Blue")
#@gimp : Keep colors = bool(1)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")

#@gimp Bayer reconstruction : bayer2rgb, gimp_no_preview
#@gimp : G/M smoothness = _float(6,0,20)
#@gimp : R/B smoothness (principal) = _float(6,0,20)
#@gimp : R/B smoothness (secondary) = _float(4,0,20)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")

#@gimp Gaussian blur : gimp_gaussian_blur, gimp_gaussian_blur_preview(0)
#@gimp : XY-amplitude = float(3,0,20)
#@gimp : X-amplitude = float(0,0,20)
#@gimp : Y-amplitude = float(0,0,20)
#@gimp : Border conditions = choice(1,"Black","Nearest")
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : Value range = choice("Cut","Normalize")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
_gimp_gaussian_blur :
  -b $1,$4
  -if {$2>0} -repeat @# -l[-1] -s y -b $2,$4 -a y -endl -mv[-1] 0 -done -endif
  -if {$3>0} -repeat @# -l[-1] -s x -b $3,$4 -a x -endl -mv[-1] 0 -done -endif

gimp_gaussian_blur :
  -apply_channels "-_gimp_gaussian_blur $1,$2,$3,$4",$5,$6

gimp_gaussian_blur_preview :
  -gimp_split_preview "-gimp_gaussian_blur ${1--2}",$-1

#@gimp Linear blur : gimp_blur_linear, gimp_blur_linear_preview(1)
#@gimp : Tangent radius = float(10,0,100)
#@gimp : Orthogonal radius = float(0.5,0,100)
#@gimp : Angle = float(0,0,180)
#@gimp : Sharpness = float(0,0,500)
#@gimp : Border conditions = choice(1,"Black","Nearest")
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : Value range = choice("Cut","Normalize")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_blur_linear :
  -apply_channels "-blur_linear $1,{$2*$1/100},$3,$5 -sharpen $4",$6,$7

gimp_blur_linear_preview :
  -gimp_split_preview "-gimp_blur_linear ${1--2}",$-1

#@gimp Old-movie stripes : gimp_stripes_y, gimp_stripes_y_preview(1)
#@gimp : Frequency = float(10,0,100)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_stripes_y :
  -apply_channels "-stripes_y $1",$2,0

gimp_stripes_y_preview :
  -gimp_split_preview "-gimp_stripes_y ${1--2}",$-1

#@gimp Oldschool 8bits : gimp_8bits, gimp_8bits_preview(0)
#@gimp : Scale = float(25,1,100)
#@gimp : Dithering = float(800,0,10000)
#@gimp : Levels = int(16,2,256)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2011/11/02</i>.</small>")
gimp_8bits :
  -to_rgb
  -repeat @#
    w={w} h={h}
    -resize[-1] $1%,$1%,1,100%,2
    --luminance[-1] -sharpen[-1] $2 -otsu[-1] 256 -compose_shapeaverage[-2,-1] -quantize[-1] $3
    -resize[-1] $w,$h,1,100%,1
  -mv[-1] 0 -done

gimp_8bits_preview :
  -gimp_split_preview "-gimp_8bits ${1--2}",$-1

#@gimp Radial blur : gimp_blur_radial, gimp_blur_radial(1)
#@gimp : Amplitude = float(3,0,20)
#@gimp : X-center = float(0.5,0,1)
#@gimp : Y-center = float(0.5,0,1)
#@gimp : Sharpness = float(0,0,500)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : Value range = choice("Cut","Normalize")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_blur_radial :
  -apply_channels "-blur_radial $1%,$2,$3 -sharpen $4",$5,$6

#@gimp Random shade stripes : gimp_shade_stripes, gimp_shade_stripes_preview(1)
#@gimp : Frequency = float(30,1,100)
#@gimp : Orientation = choice(1,"Horizontal","Vertical")
#@gimp : Darkness = float(0.8,0,3)
#@gimp : Lightness = float(1.3,0,3)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_shade_stripes :
  -apply_channels "-shade_stripes $1,$2,$3,$4",$5,0

gimp_shade_stripes_preview :
  -gimp_split_preview "-gimp_shade_stripes ${1--2}",$-1

#@gimp Spread noise : gimp_spread, gimp_spread_preview(0)
#@gimp : X-variations = float(4,0,20)
#@gimp : Y-variations = float(4,0,20)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_spread :
  -apply_channels "-spread $1,$2",$3,0

gimp_spread_preview :
  -gimp_split_preview "-gimp_spread ${1--2}",$-1

#@gimp Visible watermark : gimp_watermark_visible, gimp_watermark_visible(0)
#@gimp : Text = text("\251 G'MIC")
#@gimp : Opacity = float(0.4,0.1,0.9)
#@gimp : Size = int(57,13,128)
#@gimp : Angle = float(25,0,360)
#@gimp : Smoothness = float(0.5,0,5)
#@gimp : Lightness = choice(1,"Darker","Brighter")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_watermark_visible :
  -watermark_visible "$1",$2,$3,$4,$6,$5


#@gimp _<b>Enhancement</b>
#--------------------------


#@gimp Anisotropic smoothing : gimp_anisotropic_smoothing, gimp_anisotropic_smoothing_preview(0)
#@gimp : Amplitude = float(60,0,1000)
#@gimp : Sharpness = float(0.7,0,2)
#@gimp : Anisotropy = float(0.3,0,1)
#@gimp : Gradient smoothness = float(0.6,0,10)
#@gimp : Tensor smoothness = float(1.1,0,10)
#@gimp : Spatial precision = float(0.8,0.1,2)
#@gimp : Angular precision = float(30,1,180)
#@gimp : Value precision = float(2,0.1,5)
#@gimp : Interpolation = choice(0,"Nearest neighbor","Linear","Runge-Kutta")
#@gimp : Fast approximation = bool(1)
#@gimp : Iterations = int(1,1,10)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : Tiles = int(1,1,10)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_anisotropic_smoothing :
  -repeat @# -l[$>]
    -split_tiles $13,$13
    -apply_channels "-repeat $11 -smooth $1,$2,$3,$4,$5,$6,$7,$8,$9,$10 -done",$12,0
    -append_tiles $13,$13
  -endl -done -c 0,255

gimp_anisotropic_smoothing_preview :
  -gimp_split_preview "-gimp_anisotropic_smoothing ${1--2}",$-1

#@gimp Bilateral filtering : gimp_bilateral, gimp_bilateral_preview(0)
#@gimp : Spatial variance = float(10,0,100)
#@gimp : Value variance = float(7,0,100)
#@gimp : Iterations = int(2,1,10)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_bilateral :
  -apply_channels "-repeat $3 -bilateral $1,$2 -done",$4,0

gimp_bilateral_preview :
  -gimp_split_preview "-gimp_bilateral ${1--2}",$-1

#@gimp Deinterlace : deinterlace, gimp_deinterlace_preview(0)
#@gimp : Algorithm = choice("Standard","Motion-compensated")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_deinterlace :
  -deinterlace 0 -skip ${^0}

gimp_deinterlace_preview :
  -gimp_split_preview "-gimp_deinterlace ${1--2}",$-1

#@gimp Deconvolution : gimp_richardson_lucy, gimp_richardson_lucy_preview(0)
#@gimp : Radius = float(2,0,20)
#@gimp : Iterations = int(10,0,100)
#@gimp : Time step = float(20,0,50)
#@gimp : Smoothness = float(0.1,0,10)
#@gimp : Regularization = choice(1,"Tikhonov","Mean curvature","Total variation")
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_richardson_lucy :
  -apply_channels "-richardson_lucy ${1-5} -c 0,255",$6,0

gimp_richardson_lucy_preview :
  -gimp_split_preview "-gimp_richardson_lucy ${1--2}",$-1

#@gimp Edge-preserving flow : gimp_edgepreserving_smoothing, gimp_edgepreserving_smoothing_preview(0)
#@gimp : Sharpness = float(0.7,0,2)
#@gimp : Anisotropy = float(0.3,0,1)
#@gimp : Gradient smoothness = float(0.6,0,10)
#@gimp : Tensor smoothness = float(1.1,0,10)
#@gimp : Time step = float(15,5,50)
#@gimp : Iterations = int(8,1,100)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_edgepreserving_smoothing :
  -apply_channels "-smooth $6,$1,$2,$3,$4,$5,0",$7,0 -c 0,255

gimp_edgepreserving_smoothing_preview :
  -gimp_split_preview "-gimp_edgepreserving_smoothing ${1--2}",$-1

#@gimp Hot pixels filtering : gimp_remove_hotpixels, gimp_remove_hotpixels_preview(0)
#@gimp : Mask size = int(3,3,20)
#@gimp : Threshold = float(10,0,200)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>J&#233;rome Boulanger</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_remove_hotpixels :
  -remove_hotpixels $1,$2

gimp_remove_hotpixels_preview :
  -gimp_split_preview "-gimp_remove_hotpixels ${1--2}",$-1

#@gimp Inverse diffusion : gimp_sharpen_inversediff, gimp_sharpen_inversediff_preview(0)
#@gimp : Amplitude = float(50,1,300)
#@gimp : Iterations = int(2,1,10)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_sharpen_inversediff :
  -apply_channels "-repeat $2 -sharpen $1 -c 0,255 -done",$3,0

gimp_sharpen_inversediff_preview :
  -gimp_split_preview "-gimp_sharpen_inversediff ${1--2}",$-1

#@gimp Mean-curvature flow : gimp_meancurvature_smoothing, gimp_meancurvature_smoothing_preview(0)
#@gimp : Time step = float(30,5,50)
#@gimp : Iterations = int(4,1,30)
#@gimp : Keep iterations as different layers = bool(false)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_meancurvature_smoothing :
  -apply_channels "-meancurvature_flow $2,$1,$3",$4,0 -c 0,255

gimp_meancurvature_smoothing_preview :
  -gimp_split_preview "-gimp_meancurvature_smoothing ${1--2}",$-1

#@gimp Median filtering : gimp_median, gimp_median_preview(0)
#@gimp : Radius = int(3,1,20)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_median :
  -apply_channels "-median $1",$2,0

gimp_median_preview :
  -gimp_split_preview "-gimp_median ${1--2}",$-1

#@gimp Octave sharpening : gimp_unsharp_octave, gimp_unsharp_octave_preview(0)
#@gimp : Scales = int(4,1,10)
#@gimp : Maximal radius = float(5,0,20)
#@gimp : Amount = float(3,0,10)
#@gimp : Threshold = float(0,0,255)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_unsharp_octave :
  -apply_channels "-unsharp_octave $1,$2,$3,$4",$5,0

gimp_unsharp_octave_preview :
  -gimp_split_preview "-gimp_unsharp_octave ${1--2}",$-1

#@gimp Patch-based smoothing : gimp_patch_smoothing, gimp_patch_smoothing_preview(0)
#@gimp : Spatial variance = float(10,0.1,200)
#@gimp : Patch variance = float(10,0.1,200)
#@gimp : Patch size = int(3,2,21)
#@gimp : Lookup size = int(5,2,21)
#@gimp : Patch smoothness = float(0,0,4)
#@gimp : Fast approximation = bool(1)
#@gimp : Iterations = int(1,1,10)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_patch_smoothing :
  -apply_channels "-repeat $7 -denoise $1,$2,$3,$4,$5,$6 -done",$8,0 -c 0,255

gimp_patch_smoothing_preview :
  -gimp_split_preview "-gimp_patch_smoothing ${1--2}",$-1

#@gimp Red-Eye attenuation : red_eye, red_eye
#@gimp : Threshold = float(75,0,100)
#@gimp : Smoothness = float(3.5,0,20)
#@gimp : Factor = float(0.1,0,1)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")

#@gimp Region inpainting : gimp_inpaint, gimp_inpaint_preview(0)
#@gimp : Smooth inpaint = bool(true)
#@gimp : Global iterations = int(10,1,30)
#@gimp : Local iterations = int(10,1,30)
#@gimp : Time step = float(20,5,50)
#@gimp : Gradient smoothness = float(0.7,0,5)
#@gimp : Tensor smoothness = float(1.2,0,5)
#@gimp : note = note("<small><b>Note :</b>
#@gimp : This filter tries to reconstruct the content of image regions.
#@gimp : The inpainted region is defined as a white area in the top layer.
#@gimp : </small>")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_inpaint :
  -if {@#==1} -return -endif
  -if $1 -inpaint_flow $2,$3,$4,$5%,$6% -c 0,255 -else -inpaint[1--1] [0] -endif
  -to_rgba[0] -f[0] 0

gimp_inpaint_preview :
  -if {@#==1} -return -endif
  -gimp_inpaint ${^0} -rm[0]

#@gimp Scale2x algorithm : gimp_scalenx, gimp_scalenx_preview(0)
#@gimp : Scaling factor = choice("x 2","x 3","x 4","x 6","x 8","x 9","x 12","x 16","x 18","x 27")
#@gimp : Colorbase = choice(1,"RGB","YCbCr","Lab")
#@gimp : note = note{"\n<small><b>Note : </b>
#@gimp : This filter re-implements the scaling algorithm described at :
#@gimp : </small>"}
#@gimp : note = link("http://scale2x.sourceforge.net")
#@gimp : note = note{"<small>
#@gimp : This filter is useful for resizing images that have very few colors
#@gimp : (e.g. indexed images). It is generally useless for true colors images.
#@gimp : </small>"}
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_scalenx :
  -repeat @# -l[$>] -split_opacity
    -if {$2==1} -rgb2ycbcr[0] -round[0]
    -elif {$2==2} -rgb2lab8[0] -round[0]
    -endif

    -if {$1==0} -resize2x
    -elif {$1==1} -resize3x
    -elif {$1==2} -resize2x -resize2x
    -elif {$1==3} -resize3x -resize2x
    -elif {$1==4} -resize2x -resize2x -resize2x
    -elif {$1==5} -resize3x -resize3x
    -elif {$1==6} -resize3x -resize2x -resize2x
    -elif {$1==7} -resize2x -resize2x -resize2x -resize2x
    -elif {$1==8} -resize3x -resize3x -resize2x
    -elif {$1==9} -resize3x -resize3x -resize3x
    -endif

    -if {$2==1} -ycbcr2rgb[0]
    -elif {$2==2} -lab82rgb[0]
    -endif

  -a c -endl -done

gimp_scalenx_preview :
  -z 40%,40%,60%,60%
  -gimp_scalenx $1,$2

#@gimp Shock filters : gimp_sharpen_shock, gimp_sharpen_shock_preview(0)
#@gimp : Amplitude = float(150,1,400)
#@gimp : Edge threshold = float(0.1,0,0.7)
#@gimp : Gradient smoothness = float(0.8,0,10)
#@gimp : Tensor smoothness = float(1.1,0,10)
#@gimp : Iterations = int(1,1,10)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_sharpen_shock :
  -apply_channels "-repeat $5 -sharpen $1,$2,$3,$4 -c 0,255 -done",$6,0

gimp_sharpen_shock_preview :
  -gimp_split_preview "-gimp_sharpen_shock ${1--2}",$-1

#@gimp Smart upscale : gimp_upscale_smart, gimp_upscale_smart_preview(0)
#@gimp : Width = text("200%")
#@gimp : Height = text("200%")
#@gimp : Smoothness = float(2,0,20)
#@gimp : Anisotropy = float(0.4,0,1)
#@gimp : Sharpness = float(50,0,100)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_upscale_smart :
  -to_rgb -upscale_smart $1,$2,1,$3,$4,$5 -c 0,255

gimp_upscale_smart_preview :
  -repeat @#
    --r[-1] $1,$2,1,1,0
    -if {w<@{-2,w}||h<@{-2,h}}  # Test for downscaling
      -rm[-1] -/[-1] 4
      1 -text[-1] "Downscaling is\nnot allowed !",5,5,20,1,255 -r[-1] [-2],[-2],1,1,0,0,0.5,0.5
      -or[-2,-1]
    -else
      -z[-2] {50-50*@{-2,w}/w}%,{50-50*@{-2,h}/h}%,{50+50*@{-2,w}/w}%,{50+50*@{-2,h}/h}%
      -rm[-1] -gimp_upscale_smart[-1] $1,$2,$3,$4,$5 -c[-1] 0,255
    -endif
  -mv[-1] 0 -done

#@gimp Solidify : gimp_solidify, gimp_solidify_preview(0)
#@gimp : Interpolation type = choice("Linear","Morphological")
#@gimp : sep = separator(), note = note("<small><b>For linear method only :</b></small>")
#@gimp : Smoothness = float(1.5,1,5)
#@gimp : Smoothness factor = float(1,1,1.2)
#@gimp : Precision = float(0.5,0,1)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small><b>Note :</b>
#@gimp : This filter replaces transparent regions by interpolated colors. It may take long to render !
#@gimp : </small>")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2011/12/01</i>.</small>")
gimp_solidify :
  -if $1 -solidify
  -else -solidify_linear $2,$3,$4
  -endif

gimp_solidify_preview :
  -gimp_split_preview "-gimp_solidify ${1--2}",$-1

#@gimp Thin brush smoothing : gimp_anisotropic_smoothing, gimp_anisotropic_smoothing(0)
#@gimp : Amplitude = float(60,0,1000)
#@gimp : Sharpness = float(0.9,0,2)
#@gimp : Anisotropy = float(0.64,0,1)
#@gimp : Gradient smoothness = float(3.1,0,10)
#@gimp : Tensor smoothness = float(1.10,0,10)
#@gimp : Spatial precision = float(0.8,0.1,2)
#@gimp : Angular precision = float(30,1,180)
#@gimp : Value precision = float(2,0.1,5)
#@gimp : Interpolation = choice(0,"Nearest neighbor","Linear","Runge-Kutta")
#@gimp : Fast approximation = bool(1)
#@gimp : Iterations = int(1,1,10)
#@gimp : Channel(s) = choice("RGB","Luminance","Blue & Red chrominances","Blue chrominance","Red chrominance")
#@gimp : Tiles = int(1,1,10)
#@gimp : note = note{"\n<small><b>Note : </b>This set of anisotropic smoothing parameters has been suggested by PhotoComiX.</small>"}
#@gimp : sep = separator(), note = note("<small>Author : <i>PhotoComiX</i>.      Latest update : <i>2010/12/26</i>.</small>")

#@gimp Total-variation flow : gimp_tv_smoothing, gimp_tv_smoothing_preview(0)
#@gimp : Time step = float(30,5,100)
#@gimp : Iterations = int(10,1,40)
#@gimp : Keep iterations as different layers = bool(false)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_tv_smoothing :
  -apply_channels "-tv_flow $2,$1,$3",$4,0 -c 0,255

gimp_tv_smoothing_preview :
  -gimp_split_preview "-gimp_tv_smoothing ${1--2}",$-1

#@gimp Unsharp mask : gimp_unsharp, gimp_unsharp_preview(0)
#@gimp : Sharpening type = choice(0,"Gaussian","Bilateral")
#@gimp : Spatial radius = float(1.25,0,20)
#@gimp : Bilateral radius = float(30,0,60)
#@gimp : Amount = float(3,0,10)
#@gimp : Threshold = float(0,0,20)
#@gimp : Darkness level = float(1,0,4)
#@gimp : Lightness level = float(1,0,4)
#@gimp : Iterations = int(1,1,10)
#@gimp : Negative effect = bool(0)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : note = note{"\n\n<small><b>Note : </b>
#@gimp : This filter is inspired by the original <i>Unsharp Mask</i> filter in GIMP, with additional parameters.
#@gimp : </small>"}
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
_gimp_unsharp :
  -repeat @# -repeat $8
    -if {$1==0} --b[-1] $2 -else --bilateral[-1] $2,$3 -endif
    --[-1] [-2] -*[-1] -$4
    --norm[-1] -t[-1] $5% -r[-1] [-2] -*[-2,-1]
    -if $9 -*[-1] -1 -endif
    --c[-1] 0,100% -c[-2] -100%,0 -*[-2] $6 -*[-1] $7 -+[-2,-1]
    -+[-2,-1] -c[-1] 0,255
  -done -mv[-1] 0 -done

gimp_unsharp :
  -apply_channels "-_gimp_unsharp $1,$2,$3,$4,$5,$6,$7,$8,$9",$10,0

gimp_unsharp_preview :
  -gimp_split_preview "-gimp_unsharp ${1--2}",$-1


#@gimp _<b>Layers</b>
#---------------------


_gimp_compose :
  -repeat {int(@#/2)} --compose_$1[-2,-1] -rm[-3] -to_rgba[-1] -sh[-1] 3,3 -*[-1] $2 -rm[-1] -compose_alpha[-2,-1] -mv[-1] 0 -done

_gimp_revert_layers :
  -repeat {int(@#/2)} -rv[{2*$>},{2*$>+1}] -done

#@gimp Alpha blending : gimp_compose_alpha, gimp_compose_alpha
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}
#@gimp : sep = separator(), note = note("<small>Author : <i>Arto Huotari, David Tschumperl&#233;</i>.      Latest update : <i>2011/10/26</i>.</small>")
gimp_compose_alpha :
  -if ${2=0} -_gimp_revert_layers -endif
  -repeat {int(@#/2)}
    -to_rgba[-1] -sh[-1] 3,3 -*[-1] $1 -rm[-1]
    -compose_alpha[-2,-1]
  -mv[-1] 0 -done

#@gimp Average : gimp_compose_average, gimp_compose_average
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_compose_average :
  -if ${2=0} -_gimp_revert_layers -endif
  -_gimp_compose average,$1

#@gimp Color burn : gimp_compose_colorburn, gimp_compose_colorburn
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_compose_colorburn :
  -if ${2=0} -_gimp_revert_layers -endif
  -_gimp_compose colorburn,$1

#@gimp Darken : gimp_compose_darken, gimp_compose_darken
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_compose_darken :
  -if ${2=0} -_gimp_revert_layers -endif
  -_gimp_compose darken,$1

#@gimp Difference : gimp_compose_difference, gimp_compose_difference
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_compose_difference :
  -if ${2=0} -_gimp_revert_layers -endif
  -to_rgb -_gimp_compose difference,$1

#@gimp Divide : gimp_compose_divide, gimp_compose_divide
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}
#@gimp : sep = separator(), note = note("<small>Author : <i>Arto Huotari</i>.      Latest update : <i>2011/10/25</i>.</small>")
gimp_compose_divide :
  -if ${2=0} -_gimp_revert_layers -endif
  -_gimp_compose divide,$1

#@gimp Dodge : gimp_compose_dodge, gimp_compose_dodge
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_compose_dodge :
  -if ${2=0} -_gimp_revert_layers -endif
  -_gimp_compose dodge,$1

#@gimp Edges : gimp_compose_edges, gimp_compose_edges(0)
#@gimp : Opacity = float(1,0,1)
#@gimp : Smoothness = float(0.8,0,5)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_compose_edges :
  -if ${3=0} -_gimp_revert_layers -endif
  -repeat {int(@#/2)} --compose_edges[-2,-1] $2 -rm[-3] -to_rgba[-1] -sh[-1] 3,3 -*[-1] $1 -rm[-1] -compose_alpha[-2,-1] -mv[-1] 0 -done

#@gimp Exclusion : gimp_compose_exclusion, gimp_compose_exclusion
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_compose_exclusion :
  -if ${2=0} -_gimp_revert_layers -endif
  -to_rgb -_gimp_compose exclusion,$1

#@gimp Fade : gimp_compose_fade, gimp_compose_fade(1)
#@gimp : Preset = choice{1,"Custom","Linear","Circular","Wave","Keftales"}
#@gimp : Offset = float(0,-1,1)
#@gimp : Thinness = float(0,0,10)
#@gimp : Sharpness = float(5,1,20)
#@gimp : Sharpest = bool(0)
#@gimp : Revert layers = bool(0)
#@gimp : Note = note{\n<small>
#@gimp : The parameters below are used in most presets.
#@gimp : </small>}
#@gimp : 1st parameter = float(0,-1,1)
#@gimp : 2nd parameter = float(0,-1,1)
#@gimp : 3rd parameter = float(0,-1,1)
#@gimp : Note = note{\n<small>
#@gimp : The formula below is used for the <i>Custom</i> preset.
#@gimp : </small>}
#@gimp : Formula = text{"cos(4*pi*x/w) * sin(4*pi*y/h)"}
#@gimp : Note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_compose_fade :
  -if {@#==1} -return -endif
  -to_colormode 4
  -if {$1==0} [0],[0],1,1,"$10"
  -else -_gimp_compose_fade$1 $7,$8,$9 -r[-1] [0],[0],1,1,3
  -endif
  -n[-1] {-(@#-2)*$3},{(@#-2)*(1+$3)}
  --[-1] {$2*(1+$3)*(@#-2)}
  -c[-1] 0,{@#-2}
  -if $6 -rv[0--2] -endif
  -if $5 -round[-1] 1
  -else -roundify[-1] $4
  -endif
  -compose_fade
  -c 0,255

_gimp_compose_fade1 : [0],[0],1,1,"a=$1*pi/2; x*cos(a) + y*sin(a)"
_gimp_compose_fade2 : [0],[0],1,1,0 -=[-1] 1,{($1+1)*50}%,{($2+1)*50}% -distance[-1] 1
_gimp_compose_fade3 : [0],[0],1,1,0 -=[-1] 1,{($1+1)*50}%,{($2+1)*50}% -distance[-1] 1 -*[-1] {0.01+$3/2} -cos[-1]
_gimp_compose_fade4 : [0],[0],1,1,"((x-w*($1+0.5))*(y-h*($2+0.5)))%(0.2*w*h*(1.001+$3))"

#@gimp Freeze : gimp_compose_freeze, gimp_compose_freeze
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_compose_freeze :
  -if ${2=0} -_gimp_revert_layers -endif
  -_gimp_compose freeze,$1

#@gimp Grain extract : gimp_compose_grainextract, gimp_compose_grainextract
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2011/01/13</i>.</small>")
gimp_compose_grainextract :
  -if ${2=0} -_gimp_revert_layers -endif
  -_gimp_compose grainextract,$1

#@gimp Grain merge : gimp_compose_grainmerge, gimp_compose_grainmerge
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2011/01/13</i>.</small>")
gimp_compose_grainmerge :
  -if ${2=0} -_gimp_revert_layers -endif
  -_gimp_compose grainmerge,$1

#@gimp Hard light : gimp_compose_hardlight, gimp_compose_hardlight
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}*
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_compose_hardlight :
  -if ${2=0} -_gimp_revert_layers -endif
  -_gimp_compose hardlight,$1

#@gimp Hue : gimp_compose_hue, gimp_compose_hue
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_compose_hue : -skip ${2=0}
  -if ${2=0} -_gimp_revert_layers -endif
  -_gimp_compose hue,$1

#@gimp Interpolation : gimp_compose_interpolation, gimp_compose_interpolation
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_compose_interpolation :
  -if ${2=0} -_gimp_revert_layers -endif
  -_gimp_compose interpolation,$1

#@gimp Lighten : gimp_compose_lighten, gimp_compose_lighten
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_compose_lighten :
  -if ${2=0} -_gimp_revert_layers -endif
  -_gimp_compose lighten,$1

#@gimp Lightness : gimp_compose_lightness, gimp_compose_lightness
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2011/04/08</i>.</small>")
gimp_compose_lightness : -skip ${2=0}
  -if ${2=0} -_gimp_revert_layers -endif
  -_gimp_compose lightness,$1

#@gimp Luminance : gimp_compose_luminance, gimp_compose_luminance
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2011/04/08</i>.</small>")
gimp_compose_luminance : -skip ${2=0}
  -if ${2=0} -_gimp_revert_layers -endif
  -_gimp_compose luminance,$1

#@gimp Median : compose_median, compose_median(0)
#@gimp : sep = separator(), note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2011/10/25</i>.</small>")

#@gimp Multiply : gimp_compose_multiply, gimp_compose_multiply
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_compose_multiply :
  -if ${2=0} -_gimp_revert_layers -endif
  -_gimp_compose multiply,$1

#@gimp Negation : gimp_compose_negation, gimp_compose_negation
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_compose_negation :
  -if ${2=0} -_gimp_revert_layers -endif
  -to_rgb -_gimp_compose negation,$1

#@gimp Overlay : gimp_compose_overlay, gimp_compose_overlay
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_compose_overlay :
  -if ${2=0} -_gimp_revert_layers -endif
  -_gimp_compose overlay,$1

#@gimp Reflect : gimp_compose_reflect, gimp_compose_reflect
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_compose_reflect :
  -if ${2=0} -_gimp_revert_layers -endif
  -_gimp_compose reflect,$1

#@gimp Saturation : gimp_compose_saturation, gimp_compose_saturation
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_compose_saturation : -skip ${2=0}
  -if ${2=0} -_gimp_revert_layers -endif
  -_gimp_compose saturation,$1

#@gimp Screen : gimp_compose_screen, gimp_compose_screen
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_compose_screen :
  -if ${2=0} -_gimp_revert_layers -endif
  -_gimp_compose screen,$1

#@gimp Shape average : gimp_compose_shapeaverage, gimp_compose_shapeaverage(0)
#@gimp : Preserve shading = bool(1)
#@gimp : Transparency = bool(0)
#@gimp : Revert layers = bool(0)
#@gimp : Note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2011/10/19</i>.</small>")
gimp_compose_shapeaverage :
  -if ${3=0} -_gimp_revert_layers -endif
  -to_rgb
  -repeat {int(@#/2)}
    -rv[-2,-1]
    -if $1 -i[0] [-1] -endif
    -compose_shapeaverage[-2,-1]
    -if $1 -*[0,-1] -/[0] 255 -mv[0] @# -endif
    -if $2 -to_rgba[-1] -replace_color[-1] 0,0,0,0,0,255,0,0,0,0 -endif
  -mv[-1] 0 -done

#@gimp Soft light : gimp_compose_softlight, gimp_compose_softlight
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_compose_softlight :
  -if ${2=0} -_gimp_revert_layers -endif
  -_gimp_compose softlight,$1

#@gimp Stamp : gimp_compose_stamp, gimp_compose_stamp
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_compose_stamp :
  -if ${2=0} -_gimp_revert_layers -endif
  -_gimp_compose stamp,$1

#@gimp Value : gimp_compose_value, gimp_compose_value
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_compose_value : -skip ${2=0}
  -if ${2=0} -_gimp_revert_layers -endif
  -_gimp_compose value,$1

#@gimp Xor : gimp_compose_xor, gimp_compose_xor
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_compose_xor :
  -if ${2=0} -_gimp_revert_layers -endif
  -to_rgb -_gimp_compose xor,$1

#@gimp Transfer colors : gimp_transfer_colors, gimp_transfer_colors
#@gimp : Transfer brighness = bool(0)
#@gimp : Revert layers = bool(0)
#@gimp : Note = note{"<small><b>Note : </b>
#@gimp : The top layer contains the target colors.\n
#@gimp : This filter needs at least two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_transfer_colors :
  -if ${2=0} -_gimp_revert_layers -endif
  -transfer_colors $1

#@gimp Transparent difference : gimp_transparent_diff, gimp_transparent_diff(1)
#@gimp : Threshold = float(1,0,100)
#@gimp : Smoothness = float(0,0,10)
#@gimp : Opaque pixels = choice(0,"From 1st layer","From 2nd layer")
#@gimp : Transparent pixels = choice(1,"From same values","From different values")
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_transparent_diff :
  -if ${5=0} -_gimp_revert_layers -endif
  -repeat {int(@#/2)}
    -if $3
      --[-2] [-1] -norm[-2] -b[-2] $2% -t[-2] $1% -rv[-2,-1]
    -else
      --[-1] [-2] -norm[-1] -b[-1] $2% -t[-1] $1%
    -endif
    -if {!$4} -negative[-1] -endif
    -to_rgba[-2] -*[-2,-1]
  -mv[-1] 0 -done

#@gimp Layers alignment : gimp_align_layers, gimp_align_layers_preview
#@gimp : Alignment type = choice(0,"Rigid","Non-rigid")
#@gimp : Smoothness = float(0.7,0,1)
#@gimp : Scales = choice(0,"Auto","1","2","3","4","5","6","7","8")
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_align_layers :
  -if ${4=0} -_gimp_revert_layers -endif
  -remove_opacity
  -if $1 -register_nonrigid $2,0.1,$3
  -else ($2) -*[-1] 3 -register_rigid[0--2] @-1 -rm[-1]
  -endif

gimp_align_layers_preview :
  -gimp_align_layers $1,$2,0 -compose_edges 0.1

#@gimp Layers morphing : gimp_morph, gimp_no_preview
#@gimp : Frames = _int(10,2,100)
#@gimp : Smoothness = _float(0.2,0,2)
#@gimp : Precision = _float(0.1,0,2)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_morph :
  -if ${4=0} -_gimp_revert_layers -endif
  -to_rgb -morph $1,$2,$3

#@gimp Tiles to layers : split_tiles, gimp_split_tiles(1)
#@gimp : X-tiles = int(3,1,100)
#@gimp : Y-tiles = int(3,1,100)
#@gimp : Homogeneous tiles = _bool(false)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_split_tiles :
  -split_tiles $1,$2,$3 -k[50%]

#@gimp Layers to tiles : append_tiles, gimp_append_tiles_preview(1)
#@gimp : X-tiles = int(3,1,100)
#@gimp : Y-tiles = int(3,1,100)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_append_tiles_preview :
  -frame 1,1,0,0,0,255 -append_tiles $1,$2

#@gimp Split tones : gimp_split_tones, gimp_split_tones_preview(0)
#@gimp : Number of tones = int(3,2,10)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_split_tones :
  -repeat @#
    --tones[-1] $1 -r[-$1--1] [-{$1+1}] -*[-$1--1] [-{$1+1}] -rm[-{$1+1}]
  -mv[-$1--1] 0 -done

gimp_split_tones_preview :
  -gimp_split_tones $1 -a x


#@gimp _<b>Lights &amp; Shadows</b>
#----------------------------------

#@gimp Contrast swiss mask : gimp_contrast_swm , gimp_contrast_swm(0)
#@gimp : sep = separator ()
#@gimp : Blur the mask = float(2,0.5,10)
#@gimp : sep = separator ()
#@gimp : note = note ("Contrast Mask need the negative of the mask")
#@gimp : SKIP to use the mask to boost = bool(false)
#@gimp : note = note ("Uncheck for Contrast Mask,Check for Contrast Boost")
#@gimp : sep = separator ()
#@gimp : note = note("Merge the Mask")
#@gimp : Intensity = float (1,0,1)
#@gimp : sep = separator(), note = note("<small>Author : <i>PhotoComiX</i>.      Latest update : <i>2011/1/1 </i>.</small>")
#@gimp : note = link("Filter explained here","http://www.gimpchat.com/viewtopic.php?f=9&t=864")
gimp_contrast_swm :
-repeat @# -l[$>] -split_opacity -l[0]
 --luminance -to_rgb
  -blur_xy[1] $1,$1
  -if {$2==0} -negative[1] -elif {$2==1} -gimp_do_nothing -endif
  -reverse[-2,-1] -gimp_compose_hardlight[-2,-1] $3
-endl -a c -endl -done

#@gimp Drop shadow : gimp_drop_shadow, gimp_drop_shadow(1)
#@gimp : X-shadow = float(3,-20,20)
#@gimp : Y-shadow = float(3,-20,20)
#@gimp : Smoothness = float(1.8,0,5)
#@gimp : Angle = float(0,0,360)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_drop_shadow :
  -drop_shadow $1%,$2%,$3% -rotate $4,0

#@gimp Light glow : gimp_lightglow, gimp_lightglow_preview(0)
#@gimp : Density = float(30,0,100)
#@gimp : Amplitude = float(0.5,0,2)
#@gimp : Mode = choice(8,"Color burn","Dodge","Freeze","Grain merge","Hard light","Interpolation",
#@gimp :               "Lighten","Multiply","Overlay","Reflect","Soft light","Stamp","Value")
#@gimp : Opacity = float(0.8,0,1)
#@gimp : note = note()
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2011/02/21</i>.</small>")
_gimp_lightglow :
  -repeat @#
    --gradient_norm[-1] -t[-1] {100-$1}% -distance[-1] 1 -^[-1] $2 -*[-1] -1 -n[-1] 0,255 -rv[-2,-1]
    -__gimp_lightglow$3[-2,-1] $4
  -mv[-1] 0 -done

__gimp_lightglow0 : -gimp_compose_colorburn $1
__gimp_lightglow1 : -gimp_compose_dodge $1
__gimp_lightglow2 : -gimp_compose_freeze $1
__gimp_lightglow3 : -gimp_compose_grainmerge $1
__gimp_lightglow4 : -gimp_compose_hardlight $1
__gimp_lightglow5 : -gimp_compose_interpolation $1
__gimp_lightglow6 : -gimp_compose_lighten $1
__gimp_lightglow7 : -gimp_compose_multiply $1
__gimp_lightglow8 : -gimp_compose_overlay $1
__gimp_lightglow9 : -gimp_compose_reflect $1
__gimp_lightglow10 : -gimp_compose_softlight $1
__gimp_lightglow11 : -gimp_compose_stamp $1
__gimp_lightglow12 : -gimp_compose_value $1

gimp_lightglow :
  -apply_channels "-_gimp_lightglow ${1-4}",$5,0

gimp_lightglow_preview :
  -gimp_split_preview "-gimp_lightglow ${1--2}",$-1

#@gimp Light patch : gimp_light_patch, gimp_light_patch(0)
#@gimp : Density = int(5,2,30)
#@gimp : Darkness = float(0.7,0,1)
#@gimp : Lightness = float(2.5,1,4)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_light_patch :
  -apply_channels "-light_patch $1,$2,$3",$4,0

#@gimp Light rays : gimp_lightrays, gimp_lightrays(1)
#@gimp : Density = float(80,0,100)
#@gimp : X-center = float(0.5,0,1)
#@gimp : Y-center = float(0.5,0,1)
#@gimp : Length = float(1,0,1)
#@gimp : Attenuation = float(0.5,0,1)
#@gimp : Transparency = bool(0)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2011/01/03</i>.</small>")
gimp_lightrays :
  -lightrays ${1-5}
  -if $6 -repeat @# -r[$>] 100%,100%,1,{@{$>,s}+(@{$>,s}%2)} -done -endif

#@gimp Relief light : gimp_light_relief, gimp_light_relief(1)
#@gimp : Ambient lightness = float(0.3,0,5)
#@gimp : Specular lightness = float(0.2,0,2)
#@gimp : Specular size = float(0.2,0,1)
#@gimp : Darkness = float(0,0,1)
#@gimp : Light smoothness = float(0.5,0,5)
#@gimp : X-light = float(0.5,0,1)
#@gimp : Y-light = float(0.5,0,1)
#@gimp : Z-light = float(5,0,20)
#@gimp : Z-scale = float(0.5,0,3)
#@gimp : Opacity as bumpmap = bool(0)
#@gimp : Image smoothness = float(0,0,10)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_light_relief :
  -b $11% -light_relief ${1-10}

#@gimp Shadow patch : gimp_shadow_patch, gimp_shadow_patch(1)
#@gimp : Opacity = float(0.7,0,1)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_shadow_patch :
  -apply_channels "-shadow_patch $1",$2,0


#@gimp _<b>Patterns</b>
#-----------------------


#@gimp Canvas : gimp_canvas, gimp_canvas_preview(0)
#@gimp : note = note{"<b>First direction :</b>"}
#@gimp : Amplitude = float(70,0,300)
#@gimp : Angle = float(45,0,180)
#@gimp : Sharpness = float(400,0,2000)
#@gimp : note = note{"\n<b>Second direction : </b>"}
#@gimp : Activate second direction = bool(true)
#@gimp : Amplitude = float(70,0,300)
#@gimp : Angle = float(135,0,180)
#@gimp : Sharpness = float(400,0,2000)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_canvas :
  -repeat @# -l[-1]
    -if $4
      ({cos($2*pi/180)}^{sin($2*pi/180)}) -vector2tensor[-1] -r[-1] [-2],[-2] --smooth[-2] [-1],$1 -rm[-2] -sharpen[-1] $3 -c[-1] 0,255
      ({cos($6*pi/180)}^{sin($6*pi/180)}) -vector2tensor[-1] -r[-1] [-2],[-2] -smooth[-3] [-1],$5 -rm[-1] -sharpen[-2] $7 -c[-2] 0,255 -+[-2,-1] -/[-1] 2
    -else
      ({cos($2*pi/180)}^{sin($2*pi/180)}) -vector2tensor[-1] -r[-1] [-2],[-2] -smooth[-2] [-1],$1 -rm[-1] -sharpen[-1] $3 -c[-1] 0,255
    -endif
  -endl -mv[-1] 0 -done

gimp_canvas_preview :
  -gimp_split_preview "-gimp_canvas ${1--2}",$-1

#@gimp Canvas texture : texturize_canvas, texturize_canvas(0)
#@gimp : Amplitude = float(20,0,256)
#@gimp : Fibrousness = float(3,0,20)
#@gimp : Emboss = float(0.6,0,1)

#@gimp Chessboard : gimp_chessboard, gimp_chessboard_preview(0)
#@gimp : First size = int(64,1,512)
#@gimp : Second size = int(64,1,512)
#@gimp : First offset = int(0,0,512)
#@gimp : Second offset = int(0,0,512)
#@gimp : Angle = float(0,0,180)
#@gimp : Opacity = float(1,0,1)
#@gimp : First color = color(0,0,0,255)
#@gimp : Second color = color(255,255,255,255)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_chessboard :
  -to_rgba -chessboard ${1-14}

gimp_chessboard_preview :
  -gimp_split_preview "-gimp_chessboard ${1--2}",$-1

#@gimp Cracks : gimp_cracks, gimp_cracks_preview(0)
#@gimp : Density = float(1,0.1,10)
#@gimp : Amplitude = float(-80,-255,255)
#@gimp : Relief = bool(true)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_cracks :
  -apply_channels "-cracks $1,$2,$3",$4,0

gimp_cracks_preview :
  -gimp_split_preview "-gimp_cracks ${1--2}",$-1

#@gimp Dices : gimp_dices, gimp_dices(0)
#@gimp : Resolution = float(2,1,10)
#@gimp : Size = int(24,8,64)
#@gimp : Color model = choice(1,"Black dices","White dices")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2011/12/13</i>.</small>")
gimp_dices :
    # Prepare input images.
    -luminance -r {100*$1/$2}%,{100*$1/$2}%,1,1,2 -quantize 6,0

    # Create dice patterns.
    -repeat 6 {2*$2},{2*$2} -_dice$> -done
    -if $3 -negative -endif
    -to_rgb[-1] -frame_round[-6--1] 10,10,0,0,128,128,128,0
    -r2dy[-6--1] $2 -a[-6--1] x

    # Convert input image to dices pattern.
    -repeat {@#-1}
      -*[-2] $2 -channels[-2] 0,1 -r[-2] {$2*100}%,{$2*100}%
      $2,$2,1,2,'if(c,y,x)' -r[-1] [-3],[-3],1,2,0,2 -+[-3,-1] --warp[-1] [-2],0,0 -rm[-3]
    -mv[-1] 0 -done
    -rm[-1]

_dice0 : -ellipse[-1] 50%,50%,5.2%,5.2%,0,1,255
_dice1 : -ellipse[-1] 25%,25%,5.2%,5.2%,0,1,255 -ellipse[-1] 75%,75%,5.2%,5.2%,0,1,255
_dice2 : -_dice1 -_dice0
_dice3 : -_dice1 -ellipse[-1] 25%,75%,5.2%,5.2%,0,1,255 -ellipse[-1] 75%,25%,5.2%,5.2%,0,1,255
_dice4 : -_dice3 -_dice0
_dice5 : -_dice3 -ellipse[-1] 25%,50%,5.2%,5.2%,0,1,255 -ellipse[-1] 75%,50%,5.2%,5.2%,0,1,255

#@gimp Dots : gimp_dots, gimp_dots_preview(0)
#@gimp : Number of scales = int(10,1,20)
#@gimp : Resolution = float(10,1,100)
#@gimp : Radius = float(3,0.1,10)
#@gimp : Stencil type = choice(2,"Black & White","RGB","Color")
#@gimp : Transparency = bool(0)
#@gimp : Negative = bool(0)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_dots :
  -v -
  -if $6 -* -1 -+ 255 -endif
  -if {$4==0} -norm -dotsbw $1,$2,$3 -* 255
  -elif {$4==1} -dotsbw $1,$2,$3 -* 255
  -else -repeat @#
    --norm[-1] -dotsbw[-1] $1,$2,$3 -compose_shapeaverage[-2,-1]
  -mv[-1] 0 -done -endif
  -if $5 -to_rgba -replace_color 0,0,0,0,0,255,0,0,0,0 -endif
  -if $6 -* -1 -+ 255 -endif

gimp_dots_preview :
  -gimp_split_preview "-gimp_dots ${1--2}",$-1

#@gimp Hearts : gimp_hearts, gimp_hearts_preview(0)
#@gimp : Density = float(10,0,100)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_hearts :
  -apply_channels "-hearts $1",$2,0

gimp_hearts_preview :
  -gimp_split_preview "-gimp_hearts ${1--2}",$-1

#@gimp Lissajous : gimp_lissajous, gimp_lissajous(1)
#@gimp : Resolution = int(4096,2,8192)
#@gimp : sep = separator()
#@gimp : X-size = float(0.9,0,2)
#@gimp : Y-size = float(0.9,0,2)
#@gimp : Z-size = float(3,1,10)
#@gimp : sep = separator()
#@gimp : X-multiplier = float(8,0,32)
#@gimp : Y-multiplier = float(7,0,32)
#@gimp : Z-multiplier = float(0,0,32)
#@gimp : sep = separator()
#@gimp : X-offset = float(0,0,1)
#@gimp : Y-offset = float(0,0,1)
#@gimp : Z-offset = float(0,0,1)
#@gimp : sep = separator()
#@gimp : X-angle = float(0,0,360)
#@gimp : Y-angle = float(0,0,360)
#@gimp : Z-angle = float(0,0,360)
#@gimp : sep = separator()
#@gimp : Thickness = float(0,0,50)
#@gimp : Color = color(255,255,255,255)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2011/04/18</i>.</small>")
gimp_lissajous :
  -repeat @# -l[$>] -to_rgba
    {w},{h}
    -f3d {0.5*max(w,h)/tan($4*pi/360)}
    -lissajous3d $1,$5,$8,$6,$9,$7,$10
    -r3d[-1] 0,0,1,$13 -r3d[-1] 0,1,0,$12 -r3d[-1] 1,0,0,$11
    -*3d[-1] {0.5*$2*@{-2,w}},{0.5*$3*@{-2,h}},{0.5*$4*max(@{-2,w},@{-2,h})}
    -col3d[-1] 1,1,1 -object3d[-2] [-1],50%,50%,0,1,0 -rm[-1]
    -distance[-1] 1 -gt[-1] $14% -*[-2] [-1] -eq[-1] 0
    -r[-1] 100%,100%,1,4
    -sh[-1] 0,0 -*[-1] $15 -rm[-1]
    -sh[-1] 1,1 -*[-1] $16 -rm[-1]
    -sh[-1] 2,2 -*[-1] $17 -rm[-1]
    -sh[-1] 3,3 -*[-1] $18 -rm[-1]
    -+[-2,-1]
  -endl -done

#@gimp Marble : gimp_marble, gimp_marble
#@gimp : Image weight = float(.5,0,30)
#@gimp : Pattern weight = float(1,0,30)
#@gimp : Pattern angle = float(0,0,360)
#@gimp : Amplitude = float(0,0,1000)
#@gimp : Sharpness = float(.4,0,5)
#@gimp : Anisotropy = float(.6,0,1)
#@gimp : Alpha = float(.6,0,20)
#@gimp : Sigma = float(1.1,0,20)
#@gimp : Cut low = float(0,0,100)
#@gimp : Cut high = float(100,0,100)
#@gimp : sep = separator(), note = note("<small>Author : <i>Preben Soeberg</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_marble :
  -marble $1/10,$2/10,$3,$4,$5,$6,$7,$8,$9%,$10%

#@gimp Mosaic : gimp_mosaic, gimp_mosaic_preview(0)
#@gimp : Density = float(1,0.1,10)
#@gimp : Keep edges = bool(true)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_mosaic :
  -apply_channels "-mosaic $1,$2",$3,0

gimp_mosaic_preview :
  -gimp_split_preview "-gimp_mosaic ${1--2}",$-1

#@gimp Paper texture : gimp_paper, gimp_paper_preview(0)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_paper :
  -apply_channels "-texturize_paper",$1,0

gimp_paper_preview :
  -gimp_split_preview "-gimp_paper ${1--2}",$-1

#@gimp Plaid : gimp_plaid_texture,gimp_plaid_texture(1)
#@gimp : Line = float(50,0,100)
#@gimp : Number of angles = int(2,1,8)
#@gimp : Starting angle = float(0,0,360)
#@gimp : Angle range = float(90,0,360)
#@gimp : Smoothness = float(1,0,5)
#@gimp : Sharpen = float(300,0,1000)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2011/05/16</i>.</small>")
gimp_plaid_texture :
  -repeat @# -l[$>]
    w={w} h={h} s={s}
    -lines $1%
    -b $5% -sharpen $6
    -resize $w,$h,1,$s,2
    --rotate[0] $3,2,1,50%,50%
    -repeat {$2-1} --rotate[0] {$3+$4*($>+1)/($2-1)},2,1,50%,50% -+[-2,-1] -done -rm[0]
    -/ $2
  -endl -done

#@gimp Plasma : gimp_plasma, gimp_plasma(0)
#@gimp : Alpha = float(0.5,0,5)
#@gimp : Beta = float(0,0,100)
#@gimp : Scale = int(8,2,10)
#@gimp : Randomize = bool(0)
#@gimp : Transparency = bool(0)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2011/03/20</i>.</small>")
gimp_plasma : -skip ${4=0},${5=0}
  -if $5 -to_rgba -else -to_rgb -endif
  -if $4 -rand 0,255 -endif
  -plasma $1,$2,$3 -n 0,255

#@gimp Polka dots : gimp_polka_dots, gimp_polka_dots(1)
#@gimp : Size = float(80,0,100)
#@gimp : Density = float(20,0.1,100)
#@gimp : First offset = float(50,0,100)
#@gimp : Second offset = float(50,0,100)
#@gimp : Angle = float(0,0,180)
#@gimp : Aliasing = float(0.5,0.1,1)
#@gimp : Shading = float(0.1,0.1,1)
#@gimp : Opacity = float(1,0,1)
#@gimp : Color = color(255,0,0,255)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_polka_dots :
  -to_rgba -polka_dots {$1*$2/100},${2--1}

#@gimp Puzzle : gimp_puzzle, gimp_puzzle_preview(0)
#@gimp : Scale = float(6,1,20)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_puzzle :
  -apply_channels "-puzzle $1",$2,0

gimp_puzzle_preview :
  -gimp_split_preview "-gimp_puzzle ${1--2}",$-1

#@gimp Rorschach : gimp_rorschach, gimp_rorschach
#@gimp : Scale = float(3,0,30)
#@gimp : Mirroring = choice(1,"None","X-axis","Y-axis","XY-axes")
#@gimp : Colored = bool(false)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2011/03/12</i>.</small>")
gimp_rorschach :
  -repeat @#
    -if $3 -to_rgb[-1] -else -to_gray[-1] -endif
    -rorschach $1%,$2 -* 255
  -mv[-1] 0 -done

#@gimp Sierpinski triangle : sierpinski, sierpinski(1)
#@gimp : Recursions = int(6,0,10)
#@gimp : 1st X-coord = float(50,0,100)
#@gimp : 1st Y-coord = float(0,0,100)
#@gimp : 2nd X-coord = float(0,0,100)
#@gimp : 2nd Y-coord = float(100,0,100)
#@gimp : 3rd X-coord = float(100,0,100)
#@gimp : 3rd Y-coord = float(100,0,100)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")

#@gimp Snowflake : snowflake, snowflake(1)
#@gimp : Recursions = int(3,0,5)
#@gimp : 1st X-coord = float(20,0,100)
#@gimp : 1st Y-coord = float(70,0,100)
#@gimp : 2nd X-coord = float(80,0,100)
#@gimp : 2nd Y-coord = float(70,0,100)
#@gimp : 3rd X-coord = float(50,0,100)
#@gimp : 3rd Y-coord = float(10,0,100)
#@gimp : Opacity = float(1,0,1)
#@gimp : Color = color(255,255,255)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")

#@gimp Sponge : gimp_sponge, gimp_sponge_preview(0)
#@gimp : Size = int(13,3,21)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_sponge :
  -apply_channels "-sponge $1",$2,0

gimp_sponge_preview :
  -gimp_split_preview "-gimp_sponge ${1--2}",$-1

#@gimp Stained glass : gimp_stained_glass, gimp_stained_glass_preview(0)
#@gimp : Edges = float(20,0,100)
#@gimp : Shading = float(0.1,0,0.5)
#@gimp : Thin separators = bool(1)
#@gimp : sep = separator()
#@gimp : Equalize = bool(1)
#@gimp : Colors = float(1,0,3)
#@gimp : Gamma = float(1,0.01,5)
#@gimp : Contrast = float(1,0,4)
#@gimp : Brightness = float(0,-255,255)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2011/03/18</i>.</small>")
gimp_stained_glass :
  -repeat @# -l[$>] -split_opacity -l[0]
    -stained_glass $1,$2,$3
    -n 0,255
    -if $4 -equalize[-1] 256 -endif
    -rgb2lab[-1] -sh[-1] 1,2 -*[-1] $5 -rm[-1] -lab2rgb[-1]
    -apply_gamma[-1] $6 --[-1] 128 -*[-1] $7 -+[-1] {128+$8}
    -c[-1] 0,255
  -endl -append c -endl -done

gimp_stained_glass_preview :
  -gimp_split_preview "-gimp_stained_glass ${1--2}",$-1

#@gimp Stencil : gimp_stencil, gimp_stencil_preview(0)
#@gimp : Radius = float(3,0,10)
#@gimp : Smoothness = float(0,0,30)
#@gimp : Iterations = int(8,1,100)
#@gimp : Aliasing = float(0,0,5)
#@gimp : Stencil type = choice(2,"Black & White","RGB","Color")
#@gimp : Transparency = bool(0)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")gimp_stencil :
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_stencil :
  -v -
  -if {$5==0} -norm -stencil $1,$2,$3
  -elif {$5==1} -stencil $1,$2,$3
  -else -repeat @#
    --norm[-1] -stencil[-1] $1,$2,$3 -t[-1] 50% -compose_shapeaverage[-2,-1]
  -mv[-1] 0 -done -endif
  -if $6 -to_rgba -replace_color 0,0,0,0,0,255,0,0,0,0 -endif
  -if $4 -smooth {30*$4},0,1,1 -endif

gimp_stencil_preview :
  -gimp_split_preview "-gimp_stencil ${1--2}",$-1

#@gimp Superformula : gimp_superformula, gimp_superformula(1)
#@gimp : Resolution = int(4096,2,8192)
#@gimp : sep = separator()
#@gimp : X-size = float(0.9,0,2)
#@gimp : Y-size = float(0.9,0,2)
#@gimp : sep = separator()
#@gimp : m = int(8,1,32)
#@gimp : n1 = float(1,-32,32)
#@gimp : n2 = float(5,-32,32)
#@gimp : n3 = float(8,-32,32)
#@gimp : sep = separator()
#@gimp : X-angle = float(0,0,360)
#@gimp : Y-angle = float(0,0,360)
#@gimp : Z-angle = float(0,0,360)
#@gimp : sep = separator()
#@gimp : Thickness = float(0,0,50)
#@gimp : Color = color(255,255,255,255)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2011/04/18</i>.</small>")
gimp_superformula :
  -repeat @# -l[$>] -to_rgba
    {w},{h}
    -f3d {0.5*max(w,h)/tan($4*pi/360)}
    -superformula3d $1,${4-7}
    -r3d[-1] 0,0,1,$10 -r3d[-1] 0,1,0,$9 -r3d[-1] 1,0,0,$8
    -*3d[-1] {0.5*$2*@{-2,w}},{0.5*$3*@{-2,h}}
    -col3d[-1] 1,1,1 -object3d[-2] [-1],50%,50%,0,1,0 -rm[-1]
    -distance[-1] 1 -gt[-1] $11% -*[-2] [-1] -eq[-1] 0
    -r[-1] 100%,100%,1,4
    -sh[-1] 0,0 -*[-1] $12 -rm[-1]
    -sh[-1] 1,1 -*[-1] $13 -rm[-1]
    -sh[-1] 2,2 -*[-1] $14 -rm[-1]
    -sh[-1] 3,3 -*[-1] $15 -rm[-1]
    -+[-2,-1]
  -endl -done

#@gimp Truchet : gimp_truchet, gimp_truchet(0)
#@gimp : Scale = int(32,1,256)
#@gimp : Radius = int(5,1,64)
#@gimp : Smoothness = float(1,0,10)
#@gimp : Type = choice(1,"Straight","Curved")
#@gimp : Colorize randomly = bool(0)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2011/10/26</i>.</small>")
gimp_truchet :
  -truchet $1,$2,$4
  -if $5 -repeat @# -channels[-1] 0 -label[-1] 0,1 {iM+1},1,1,3 -rand[-1] 0,255 -map[-2] [-1] -rm[-1] -mv[-1] 0 -done -endif
  -b $3 -n 0,255

#@gimp Turbulence : gimp_turbulence, gimp_turbulence
#@gimp : Radius = float(128,1,1024)
#@gimp : Octaves = int(6,1,12)
#@gimp : Damping per octave = float(4,1,10)
#@gimp : Difference mixing = float(0,-10,10)
#@gimp : Mode = choice("Turbulence","Turbulence 2","Fractal Noise","Fractured Clouds","Stardust","Pea Soup")
#@gimp : sep = separator(), note = note("<small>Author : <i>Preben Soeberg</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_turbulence :
  -turbulence ${^0}

#@gimp Whirls : gimp_whirls, gimp_whirls_preview(0)
#@gimp : Density = int(7,3,20)
#@gimp : Smoothness = float(2,0,10)
#@gimp : Darkness = float(0.2,0,1)
#@gimp : Lightness = float(1.8,1,3)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_whirls :
  -apply_channels "-whirls $1,$2,$3,$4",$5,0

gimp_whirls_preview :
  -gimp_split_preview "-gimp_whirls ${1--2}",$-1


#@gimp _<b>Testing</b>
#---------------------

#@gimp PhotoComiX
#@gimp PhotoComiX smoothing : gimp_anisotropic_smoothing, gimp_anisotropic_smoothing(0)
#@gimp : Amplitude = float(60,0,1000)
#@gimp : Sharpness = float(0.16,0,2)
#@gimp : Anisotropy = float(0.63,0,1)
#@gimp : Gradient smoothness = float(0.6,0,10)
#@gimp : Tensor smoothness = float(2.35,0,10)
#@gimp : Spatial precision = float(0.8,0.1,2)
#@gimp : Angular precision = float(30,1,180)
#@gimp : Value precision = float(2,0.1,5)
#@gimp : Interpolation = choice(0,"Nearest neighbor","Linear","Runge-Kutta")
#@gimp : Fast approximation = bool(1)
#@gimp : Iterations = int(1,1,10)
#@gimp : Channel(s) = choice("RGB","Luminance","Blue & Red chrominances","Blue chrominance","Red chrominance")
#@gimp : Tiles = int(1,1,10)
#@gimp : note = note{"\n<small><b>Note : </b>This set of anisotropic smoothing parameters has been suggested by PhotoComiX.</small>"}
#@gimp : sep = separator(), note = note("<small>Author : <i>PhotoComiX</i>.      Latest update : <i>2010/12/29</i>.</small>")
#@gimp _

#@gimp Lylejk
#@gimp Lylejk's stencil : gimp_lylejk_stencil, gimp_lylejk_stencil(0)
#@gimp : Amplitude = int(5,1,10)
#@gimp : Sharpness = float(10,0,100)
#@gimp : Radius = float(3,0,10)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), note = note("<small>Authors : <i>Lyle Kroll, David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_lylejk_stencil :
  -apply_channels "-repeat $1 -b $3 -unsharp $3,$2 -c 0,255 -mv[-1] 0 -done",$4,0
#@gimp _

#@gimp _<b>Rendering</b>
#------------------------


# Generic function to render a 3d image, with usual rendering parameters :
# $1 = Width
# $2 = Height
# $3 = Object size
# $4 = X-angle
# $5 = Y-angle
# $6 = Z-angle
# $7 = FOV
# $8 = X-light
# $9 = Y-light
# $10 = Z-light
# $11 = Specularity
# $12 = Shininess
# $13 = Rendering mode.
gimp_render3d :
  -n3d -c3d -m3d $13 f3d={0.5*max($1,$2)/tan($7*pi/360)}
  -f3d $f3d -l3d {$8*$f3d},{$9*$f3d},{$10*$f3d} -sl3d $11 -ss3d $12
  -repeat @# -l[$>]
    -*3d {$3*max($1,$2)} -r3d 0,0,1,$6 -r3d 0,1,0,$5 -r3d 1,0,0,$4
    $1,$2,1,3,-1 -object3d[-1] [-2],50%,50% -rm[-2]
    -to_rgba -replace_color 0,0,-1,-1,-1,255,0,0,0,0
  -endl -done

#@gimp 3d colored object : gimp_coloredobject3d, gimp_coloredobject3d_preview(1)
#@gimp : Type = choice{1,"Plane","Box","Pyramid","Ellipsoid","Torus","Gyroid","Weird","Cup"}
#@gimp : Color = color(128,128,128,255)
#@gimp : sep = separator()
#@gimp : Size-1 = float(0.5,0,3)
#@gimp : Size-2 = float(0.5,0,3)
#@gimp : Size-3 = float(0.5,0,3)
#@gimp : X-angle = float(57,0,360)
#@gimp : Y-angle = float(41,0,360)
#@gimp : Z-angle = float(21,0,360)
#@gimp : FOV = float(45,1,90)
#@gimp : X-light = float(0,-100,100)
#@gimp : Y-light = float(0,-100,100)
#@gimp : Z-light = float(-100,-100,0)
#@gimp : Specularity = float(0.5,0,1)
#@gimp : Shininess = float(0.7,0,3)
#@gimp : Rendering = choice(4,"Dots","Wireframe","Flat","Flat shaded","Gouraud","Phong")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2011/05/16</i>.</small>")
_gimp_coloredobject3d :
  -to_rgb -_gimp_coloredobject3d$1$2 ${6-8} -col3d[-1] ${3-5}
  -db3d 0

gimp_coloredobject3d :
  -_gimp_coloredobject3d "_",${1-4,6-8}
  -repeat {@#-1}
    --gimp_render3d[-1] @{$>,w},@{$>,h},$6,${9--1}
    -sh[-1] 3,3 -*[-1] {$5/255} -rm[-1]
    -compose_alpha[$>,-1]
  -done
  -rm[-1]

gimp_coloredobject3d_preview :
  -_gimp_coloredobject3d "_preview_",${1-4,6-8}
  -repeat {@#-1}
    --gimp_render3d[-1] @{$>,w},@{$>,h},$6,${9--1}
    -sh[-1] 3,3 -*[-1] {$5/255} -rm[-1]
    -compose_alpha[$>,-1]
  -done -rm[-1]

_gimp_coloredobject3d_0 : -plane3d 1 -*3d[-1] $1,$2,1
_gimp_coloredobject3d_1 : -box3d 1 -*3d[-1] $1,$2,$3
_gimp_coloredobject3d_2 : -pyramid3d 1,1 -*3d[-1] $1,$2,$3
_gimp_coloredobject3d_3 : -sphere3d 1 -*3d[-1] 1,{2*$2},{2*$3}
_gimp_coloredobject3d_4 : -torus3d $1,{$2/2} -*3d[-1] $3,1,1
_gimp_coloredobject3d_5 : -gyroid3d 24 -*3d[-1] $1,$2,$3
_gimp_coloredobject3d_6 : -weird3d 32 -*3d[-1] $1,$2,$3
_gimp_coloredobject3d_7 : -cup3d 128 -*3d[-1] $1,$2,$3
_gimp_coloredobject3d_preview_0 : -plane3d 1 -*3d[-1] $1,$2,1
_gimp_coloredobject3d_preview_1 : -box3d 1 -*3d[-1] $1,$2,$3
_gimp_coloredobject3d_preview_2 : -pyramid3d 1,1 -*3d[-1] $1,$2,$3
_gimp_coloredobject3d_preview_3 : -sphere3d 1 -*3d[-1] 1,{2*$2},{2*$3}
_gimp_coloredobject3d_preview_4 : -torus3d $1,{$2/2} -*3d[-1] $3,1,1
_gimp_coloredobject3d_preview_5 : -gyroid3d 8 -*3d[-1] $1,$2,$3
_gimp_coloredobject3d_preview_6 : -weird3d 12 -*3d[-1] $1,$2,$3
_gimp_coloredobject3d_preview_7 : -cup3d 64 -*3d[-1] $1,$2,$3

#@gimp 3d elevation : gimp_elevation3d, gimp_elevation3d_preview(1)
#@gimp : Factor = float(100,-1000,1000)
#@gimp : Smoothness = float(1,0,10)
#@gimp : sep = separator()
#@gimp : Width = _int(1024,8,4096)
#@gimp : Height = _int(1024,8,4096)
#@gimp : Size = float(0.8,0,3)
#@gimp : X-angle = float(25,0,360)
#@gimp : Y-angle = float(0,0,360)
#@gimp : Z-angle = float(21,0,360)
#@gimp : FOV = float(45,1,90)
#@gimp : X-light = float(0,-100,100)
#@gimp : Y-light = float(0,-100,100)
#@gimp : Z-light = float(-100,-100,0)
#@gimp : Specularity = float(0.5,0,1)
#@gimp : Shininess = float(0.7,0,3)
#@gimp : Rendering = choice(2,"Dots","Wireframe","Flat","Flat shaded","Gouraud","Phong")
#@gimp : sep = separator(), note = note{"<small><b>Note :</b> Add a top layer to define object texture.</small>"}
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
_gimp_elevation3d :
  -repeat {@#/2} -l[$>,{min($>+1,@#-1)}]
    -if {@#==1} --norm -else -r[1] [0],3 -endif
    -n[1] 0,$1 -b[1] $2
    -elevation3d[0] [1] -rm[1]
  -endl -done
  -db3d 1

gimp_elevation3d :
  -_gimp_elevation3d ${1-2} -gimp_render3d ${3--1}

gimp_elevation3d_preview :
  -gimp_elevation3d ${1-2},{w},{h},${5--1}

#@gimp 3d extrusion : gimp_extrude3d, gimp_extrude3d_preview(1)
#@gimp : Depth = float(10,1,1024)
#@gimp : Resolution = int(512,1,1024)
#@gimp : Smoothness = float(0.6,0,3)
#@gimp : sep = separator()
#@gimp : Width = _int(1024,1,4096)
#@gimp : Height = _int(1024,1,4096)
#@gimp : Size = float(0.5,0,3)
#@gimp : X-angle = float(57,0,360)
#@gimp : Y-angle = float(41,0,360)
#@gimp : Z-angle = float(21,0,360)
#@gimp : FOV = float(45,1,90)
#@gimp : X-light = float(0,-100,100)
#@gimp : Y-light = float(0,-100,100)
#@gimp : Z-light = float(-100,-100,0)
#@gimp : Specularity = float(0.5,0,1)
#@gimp : Shininess = float(0.7,0,3)
#@gimp : Rendering = choice(4,"Dots","Wireframe","Flat","Flat shaded","Gouraud","Phong")
#@gimp : sep = separator(), note = note{"<small><b>Note :</b> Add a top layer to define object texture.</small>"}
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
_gimp_extrude3d :
  -repeat {@#/2} -l[$>,{min($>+1,@#-1)}]
    -extrude3d[-1] $1,$2,$3%
    -if {@#==2} -t3d[-1] [-2] -rm[-2] -endif
  -endl -done
  -db3d 0

gimp_extrude3d :
  -_gimp_extrude3d ${1-3} -gimp_render3d ${4--1}

gimp_extrude3d_preview :
  -gimp_extrude3d ${1-3},{w},{h},${6--1}

#@gimp 3d image object : gimp_imageobject3d, gimp_imageobject3d_preview(1)
#@gimp : Type = choice{1,"Plane","Cube","Pyramid","Sphere","Torus","Gyroid","Weird","Cup","Rubik"}
#@gimp : sep = separator()
#@gimp : Width = _int(1024,1,4096)
#@gimp : Height = _int(1024,1,4096)
#@gimp : Size = float(0.5,0,3)
#@gimp : X-angle = float(57,0,360)
#@gimp : Y-angle = float(41,0,360)
#@gimp : Z-angle = float(21,0,360)
#@gimp : FOV = float(45,1,90)
#@gimp : X-light = float(0,-100,100)
#@gimp : Y-light = float(0,-100,100)
#@gimp : Z-light = float(-100,-100,0)
#@gimp : Specularity = float(0.5,0,1)
#@gimp : Shininess = float(0.7,0,3)
#@gimp : Rendering = choice(4,"Dots","Wireframe","Flat","Flat shaded","Gouraud","Phong")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
_gimp_imageobject3d :
  -to_rgb -repeat @# -l[$>] -_gimp_imageobject3d$1$2 -endl -done
  -db3d 0

gimp_imageobject3d :
  -_gimp_imageobject3d "_",$1 -gimp_render3d ${2--1}

gimp_imageobject3d_preview :
  w={w} h={h} -_gimp_imageobject3d "_preview_",$1 -gimp_render3d $w,$h,${4--1}

_gimp_imageobject3d_0 : -imageplane3d
_gimp_imageobject3d_1 : -imagecube3d
_gimp_imageobject3d_2 : -imagepyramid3d
_gimp_imageobject3d_3 : -imagesphere3d 64,32
_gimp_imageobject3d_4 : -torus3d 100,30 -t3d[-1] [-2] -rm[-2]
_gimp_imageobject3d_5 : -gyroid3d 24 -t3d[-1] [-2] -rm[-2]
_gimp_imageobject3d_6 : -weird3d 32 -t3d[-1] [-2] -rm[-2]
_gimp_imageobject3d_7 : -cup3d 128 -t3d[-1] [-2] -rm[-2]
_gimp_imageobject3d_8 : -imagerubik3d 5,5
_gimp_imageobject3d_preview_0 : -imageplane3d
_gimp_imageobject3d_preview_1 : -imagecube3d
_gimp_imageobject3d_preview_2 : -imagepyramid3d
_gimp_imageobject3d_preview_3 : -imagesphere3d 16,8
_gimp_imageobject3d_preview_4 : -torus3d 100,30 -t3d[-1] [-2] -rm[-2]
_gimp_imageobject3d_preview_5 : -gyroid3d 8 -c3d[-1] -n3d[-1] -t3d[-1] [-2] -rm[-2]
_gimp_imageobject3d_preview_6 : -weird3d 12 -t3d[-1] [-2] -rm[-2]
_gimp_imageobject3d_preview_7 : -cup3d 64 -t3d[-1] [-2] -rm[-2]
_gimp_imageobject3d_preview_8 : -imagerubik3d 3,3,5,5

#@gimp 3d lathing : gimp_lathing3d, gimp_lathing3d_preview(1)
#@gimp : Resolution = int(76,1,1024)
#@gimp : Smoothness = float(0.6,0,3)
#@gimp : Max angle = float(361,0,361)
#@gimp : sep = separator()
#@gimp : Width = _int(1024,1,4096)
#@gimp : Height = _int(1024,1,4096)
#@gimp : Size = float(0.5,0,3)
#@gimp : X-angle = float(57,0,360)
#@gimp : Y-angle = float(41,0,360)
#@gimp : Z-angle = float(21,0,360)
#@gimp : FOV = float(45,1,90)
#@gimp : X-light = float(0,-100,100)
#@gimp : Y-light = float(0,-100,100)
#@gimp : Z-light = float(-100,-100,0)
#@gimp : Specularity = float(0.5,0,1)
#@gimp : Shininess = float(0.7,0,3)
#@gimp : Rendering = choice(4,"Dots","Wireframe","Flat","Flat shaded","Gouraud","Phong")
#@gimp : sep = separator(), note = note{"<small><b>Note :</b> Add a top layer to define object texture.</small>"}
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
_gimp_lathing3d :
  -repeat {@#/2} -l[$>,{min($>+1,@#-1)}]
    -lathe3d[-1] $1,$2%,$3
    -if {@#==2} -t3d[-1] [-2] -rm[-2] -endif
  -endl -done
  -db3d 0

gimp_lathing3d :
  -_gimp_lathing3d ${1-3} -gimp_render3d ${4--1}

gimp_lathing3d_preview :
  -gimp_lathing3d ${1-3},{w},{h},${6--1}

#@gimp 3d random objects : gimp_random3d, gimp_random3d(1)
#@gimp : Type = choice("Cube","Cone","Cylinder","Sphere","Torus")
#@gimp : Density = int(50,1,300)
#@gimp : Size = float(3,1,20)
#@gimp : Z-range = float(100,0,300)
#@gimp : FOV = float(45,1,90)
#@gimp : X-light = float(0,-100,100)
#@gimp : Y-light = float(0,-100,100)
#@gimp : Z-light = float(-100,-100,0)
#@gimp : Specularity = float(0.5,0,1)
#@gimp : Shininess = float(0.7,0,3)
#@gimp : Rendering = choice(3,"Dots","Wireframe","Flat","Flat shaded","Gouraud","Phong")
#@gimp : Opacity = float(1,0,1)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_random3d :
  -m3d $11 -db3d 0
  -repeat @# -l[$>]
    f3d={0.5*max(w,h)/tan($5*pi/360)} -f3d $f3d -l3d {$6*$f3d},{$7*$f3d},{$8*$f3d} -sl3d $9 -ss3d $10
    -to_rgb ({w},{h},{d},{s}) -/[-1] 2 -repeat $2
    (@{1,0}) -+[-1] @{1,1} -*[-1] $3 -/[-1] 100 -_gimp_random3d$1 @-1 -rm[-2]
    -r3d[-1] 1,1,0,{?(0,360)}
    ({?(-1,1)}) -*[-1] @{1,0} ({?(-1,1)}) -*[-1] @{1,1}
    -+3d[-3] @-2,@-1,{?(-$4,$4)} -rm[-2,-1]
    -col3d[-1] {?(255)},{?(255)},{?(255)} -done -+3d[2--1] -object3d[0] [-1],50%,50%,0,$12,1
    -k[0]
  -endl -done

_gimp_random3d0 : -box3d $1
_gimp_random3d1 : ($1) -/[-1] 2 -cone3d @-1,$1 -rm[-2]
_gimp_random3d2 : ($1) -/[-1] 2 -cylinder3d @-1,$1 -rm[-2]
_gimp_random3d3 : -sphere3d $1,2
_gimp_random3d4 : ($1) -/[-1] 3 -torus3d $1,@-1 -rm[-2]

#@gimp Equation plot : gimp_equation_plot, gimp_equation_plot
#@gimp : Equation = text{"X*c+10*cos(X+c+?)"}
#@gimp : X-min = float(-10,-100,100)
#@gimp : X-max = float(10,-100,100)
#@gimp : Resolution = int(100,2,1024)
#@gimp : Channels = int(3,1,32)
#@gimp : Plot type = choice(2,"None","Lines","Splines","Bars")
#@gimp : Vertex type = choice(0,"None","Points","Crosses 1","Crosses 2","Circles 1","Circles 2","Square 1","Square 2")
#@gimp : sep = separator()
#@gimp : note = note("<b>Note</b> :
#@gimp : Use variable 'X' instead of 'x' in the equation to take care of X-min/max settings.
#@gimp : Variable 'c' refers to the current channel number. Reduce resolution to be able to view
#@gimp : separate graph vertices.")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_equation_plot :
  -repeat @#
    w={w} h={h} -rm[-1]
    $4,1,1,$5,"X=$2+($3-$2)*x/($4-1);$1"
    -dg $w,$h,$6,$7,$2,$3
  -mv[-1] 0 -done

#@gimp Mandelbrot / Julia sets : gimp_mandelbrot, gimp_mandelbrot_preview
#@gimp : X-center = float(0,-2,2)
#@gimp : Y-center = float(0,-2,2)
#@gimp : Zoom = float(0,0,100)
#@gimp : Iterations = int(128,1,512)
#@gimp : Fractal set = choice(Mandelbrot, Julia)
#@gimp : X-seed (Julia) = text("0.317")
#@gimp : Y-seed (Julia) = text("0.03")
#@gimp : Color 1 = color(0,0,255)
#@gimp : Color 2 = color(0,255,0)
#@gimp : Color 3 = color(255,0,0)
#@gimp : Color 4 = color(255,0,255)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_mandelbrot :
  (0^0^0) ($8^$9^$10) ($11^$12^$13) ($14^$15^$16) ($17^$18^$19)
  -a[-4--1] x -r[-1] $4,1,1,3,3 -a[-2,-1] x -mv[-1] 0
  -repeat {@#-1}
    wh={w},{h} -rm[-1] $wh
    -mandelbrot[-1] {$1-2/(1+$3)},{$2-2/(1+$3)},{$1+2/(1+$3)},{$2+2/(1+$3)},$4,$5,{if($5,$6,0)},{if($5,$7,0)}
    -map[-1] [0]
  -mv[-1] 1 -done -rm[0]

gimp_mandelbrot_preview :
  -gimp_mandelbrot ${^0}
  -line 0,50%,100%,50%,0.5,255
  -line 50%,0,50%,100%,0.5,255

#@gimp Maze : gimp_maze, gimp_maze
#@gimp : Cell size = int(24,1,256)
#@gimp : Thickness = int(1,1,10)
#@gimp : Masking = choice("None","Render on dark areas","Render on white areas")
#@gimp : Preserve image dimension = bool(1)
#@gimp : Maze type = choice("Dark walls","White walls")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2011/09/02</i>.</small>")
gimp_maze :
  -repeat @#
    w={w} h={h}
    -r[-1] {100/$1}%,{100/$1}%,1,100%,2
    -if {$3==0} -f[-1] 1
    -elif {$3==1} -negative[-1]
    -endif
    -maze_mask[-1] $1 -dilate[-1] $2 -*[-1] 255
    -if {!$5} -negative[-1] -endif
    -if $4 -r[-1] $w,$h,100%,100% -endif
  -mv[-1] 0 -done

#@gimp Rainbow : gimp_rainbow, gimp_rainbow
#@gimp : Left position = float(80,0,100)
#@gimp : Right position = float(80,0,100)
#@gimp : Left slope = float(175,0,400)
#@gimp : Right slope = float(175,0,400)
#@gimp : Thinness = float(3,0.1,8)
#@gimp : Opacity = float(80,0,199)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_rainbow :
  -channels 0 -f 0
  -spline 0,$1%,100,{-$3}%,100%,$2%,100,$4%,1,1
  -flood 0,0,0,0,0,1,1 -flood {w-1},0,0,0,0,1,1
  -distance 0 -c 0,255 -n 0,{$5*255}
  -rainbow_lut --luminance[-1] -c[-1] 0,{min(100,200-$6)}% -n[-1] 0,255 -a[-2,-1] c
  -map[0--2] [-1] -rm[-1]
  -if {$6<100} -repeat @# -sh[$>] 3,3 -*[-1] {$6/100} -rm[-1] -done -endif

#@gimp Shade bobs : gimp_shadebobs, gimp_shadebobs
#@gimp : note = note("<small>Bobs parameters :</small>")
#@gimp : Density = int(50,1,200)
#@gimp : Radius = int(5,1,100)
#@gimp : Duration = int(200,1,500)
#@gimp : Velocity = float(1,0,10)
#@gimp : sep = separator()
#@gimp : note = note("<small>Curve parameters :</small>")
#@gimp : Rx = float(-1,-3,3)
#@gimp : Ry = float(2,-3,3)
#@gimp : Rz = float(1,-3,3)
#@gimp : Rt = float(0.8,-3,3)
#@gimp : Rcx = float(0,-3,3)
#@gimp : Colormap = choice(8,"Grayscale","Standard","HSV","Lines","Hot","Cool","Jet","Flag","Cube")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2012/04/18</i>.</small>")
gimp_shadebobs :
  -channels 0 -f 0
  -repeat @# -l[$>]
    t=0
    -repeat $3
      -repeat $1
        r={$6+$5*cos(6*$7*$t)+(1-$5)*sin(6*$8*$t)}
        a={(360*sin($7*$t)+30*$6*$>)*pi/180}
        ax={2*$>*pi/$1+$t}
        cx={(1+$9*cos($ax)+$r*cos($a))*w/2}
        cy={(1+$9*sin($ax)+$r*sin($a))*h/2}
        -ellipse[-1] $cx,$cy,$2%,$2%,0,-1,1
      -done
      t={$t+$4/100}
    -done
  -endl -done
  -and 255 -if $10 -map {$10-1} -endif

#@gimp _<b>Sequences</b>
#-----------------------


# gimp_animate_preview : _command,_parameters1,_parameters2,_compute_half={ 0 | 1 },_width>=0,_height>=0
# Generate a preview with start/end rendering of an animation.
gimp_animate_preview : -skip ${4=1},${5=0},${6=$5}
  -repeat @#
    -if $5 width=$5 -else width={w} -endif
    -if $6 height=$6 -else height={h} -endif
    -if $4 -s[-1] x,2 -else [-1] -endif
    -$1[-2] $2 -$1[-1] $3   # Assume this is a 1->1 filter.
    -r[-2,-1] {max(w,@{-2,w})},{max(h,@{-2,h})},1,100%,3
    -if {!$4} -columns[-2] 0,50% -columns[-1] 50%,100% -endif
    -a[-2,-1] x -r[-1] $width,$height,1,100%,2 -drgba[-1]
    -line[-1] 50%,0,50%,100%,1,0,0,0,255
    -text_outline[-1] "Start",1,0,13,1,1,255 -text_outline[-1] "End",{w-23},{h-16},13,1,1,255
  -mv[-1] 0 -done

#@gimp 3d elevation : gimp_animate_elevation3d, gimp_animate_elevation3d_preview(1)
#@gimp : Frames = _int(10,2,100)
#@gimp : Output as frames = _bool(1)
#@gimp : Output as files = _bool(0)
#@gimp : Output folder = _folder()
#@gimp : note = note{"\n<b>Global parameters :</b>"}
#@gimp : Factor = float(100,-1000,1000)
#@gimp : Smoothness = float(1,0,10)
#@gimp : Width = _int(1024,8,4096)
#@gimp : Height = _int(1024,8,4096)
#@gimp : Rendering = choice(2,"Dots","Wireframe","Flat","Flat shaded","Gouraud","Phong")
#@gimp : note = note{"\n<b>Starting parameters :</b>"}
#@gimp : Size = float(0.8,0,3)
#@gimp : X-angle = float(35,0,360)
#@gimp : Y-angle = float(0,0,360)
#@gimp : Z-angle = float(0,0,360)
#@gimp : FOV = float(45,1,90)
#@gimp : X-light = float(0,-100,100)
#@gimp : Y-light = float(0,-100,100)
#@gimp : Z-light = float(-100,-100,0)
#@gimp : Specularity = float(0.5,0,1)
#@gimp : Shininess = float(0.7,0,3)
#@gimp : note = note{"\n<b>Ending parameters :</b>"}
#@gimp : Size = float(0.8,0,3)
#@gimp : X-angle = float(35,0,1440)
#@gimp : Y-angle = float(0,0,1440)
#@gimp : Z-angle = float(360,0,1440)
#@gimp : FOV = float(45,1,90)
#@gimp : X-light = float(0,-100,100)
#@gimp : Y-light = float(0,-100,100)
#@gimp : Z-light = float(-100,-100,0)
#@gimp : Specularity = float(0.5,0,1)
#@gimp : Shininess = float(0.7,0,3)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_animate_elevation3d :
  -if $3 filename="$4/gmic_elevation3d.png" -else filename="" -endif
  -_gimp_elevation3d ${5-6}
  -animate gimp_render3d,"${7-8},${10-19},$9",\
                         "${7-8},${20-29},$9",$1,$2,@{"-quote \""$filename"\""}

gimp_animate_elevation3d_preview :
  w={w} h={h}
  -_gimp_elevation3d ${5-6}
  -gimp_animate_preview gimp_render3d,$w","$h",${10-19},$9",\
                                      $w","$h",${20-29},$9",0,$w,$h

#@gimp 3d extrusion : gimp_animate_extrude3d, gimp_animate_extrude3d_preview(1)
#@gimp : Frames = _int(10,2,100)
#@gimp : Output as frames = _bool(1)
#@gimp : Output as files = _bool(0)
#@gimp : Output folder = _folder()
#@gimp : note = note{"\n<b>Global parameters :</b>"}
#@gimp : Depth = float(10,1,256)
#@gimp : Resolution = int(512,1,1024)
#@gimp : Smoothness = float(0.6,0,3)
#@gimp : Width = _int(1024,8,4096)
#@gimp : Height = _int(1024,8,4096)
#@gimp : Rendering = choice(4,"Dots","Wireframe","Flat","Flat shaded","Gouraud","Phong")
#@gimp : note = note{"\n<b>Starting parameters :</b>"}
#@gimp : Size = float(0.8,0,3)
#@gimp : X-angle = float(35,0,360)
#@gimp : Y-angle = float(0,0,360)
#@gimp : Z-angle = float(0,0,360)
#@gimp : FOV = float(45,1,90)
#@gimp : X-light = float(0,-100,100)
#@gimp : Y-light = float(0,-100,100)
#@gimp : Z-light = float(-100,-100,0)
#@gimp : Specularity = float(0.5,0,1)
#@gimp : Shininess = float(0.7,0,3)
#@gimp : note = note{"\n<b>Ending parameters :</b>"}
#@gimp : Size = float(0.8,0,3)
#@gimp : X-angle = float(35,0,1440)
#@gimp : Y-angle = float(360,0,1440)
#@gimp : Z-angle = float(0,0,1440)
#@gimp : FOV = float(45,1,90)
#@gimp : X-light = float(0,-100,100)
#@gimp : Y-light = float(0,-100,100)
#@gimp : Z-light = float(-100,-100,0)
#@gimp : Specularity = float(0.5,0,1)
#@gimp : Shininess = float(0.7,0,3)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_animate_extrude3d :
  -if $3 filename="$4/gmic_extrude3d.png" -else filename="" -endif
  -_gimp_extrude3d ${5-7}
  -animate gimp_render3d,"${8-9},${11-20},$10",\
                         "${8-9},${21-30},$10",$1,$2,@{"-quote \""$filename"\""}

gimp_animate_extrude3d_preview :
  w={w} h={h}
  -_gimp_extrude3d ${5-7}
  -gimp_animate_preview gimp_render3d,$w","$h",${11-20},$10",\
                                      $w","$h",${21-30},$10",0,$w,$h

#@gimp 3d image object : gimp_animate_imageobject3d, gimp_animate_imageobject3d_preview(1)
#@gimp : Frames = _int(10,2,100)
#@gimp : Output as frames = _bool(1)
#@gimp : Output as files = _bool(0)
#@gimp : Output folder = _folder()
#@gimp : note = note{"\n<b>Global parameters :</b>"}
#@gimp : Type = choice{1,"Plane","Cube","Pyramid","Sphere","Torus","Gyroid","Weird","Cup","Rubik"}
#@gimp : Width = _int(1024,1,4096)
#@gimp : Height = _int(1024,1,4096)
#@gimp : Rendering = choice(4,"Dots","Wireframe","Flat","Flat shaded","Gouraud","Phong")
#@gimp : note = note{"\n<b>Starting parameters :</b>"}
#@gimp : Size = float(0.5,0,3)
#@gimp : X-angle = float(57,0,360)
#@gimp : Y-angle = float(41,0,360)
#@gimp : Z-angle = float(21,0,360)
#@gimp : FOV = float(45,1,90)
#@gimp : X-light = float(0,-100,100)
#@gimp : Y-light = float(0,-100,100)
#@gimp : Z-light = float(-100,-100,0)
#@gimp : Specularity = float(0.5,0,1)
#@gimp : Shininess = float(0.7,0,3)
#@gimp : note = note{"\n<b>Ending parameters :</b>"}
#@gimp : Size = float(0.5,0,3)
#@gimp : X-angle = float(57,0,1440)
#@gimp : Y-angle = float(401,0,1440)
#@gimp : Z-angle = float(21,0,1440)
#@gimp : FOV = float(45,1,90)
#@gimp : X-light = float(0,-100,100)
#@gimp : Y-light = float(0,-100,100)
#@gimp : Z-light = float(-100,-100,0)
#@gimp : Specularity = float(0.5,0,1)
#@gimp : Shininess = float(0.7,0,3)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_animate_imageobject3d :
  -if $3 filename="$4/gmic_imageobject3d.png" -else filename="" -endif
  -_gimp_imageobject3d "_",$5
  -animate gimp_render3d,"${6-7},${9-18},$8",\
                         "${6-7},${19-28},$8",$1,$2,@{"-quote \""$filename"\""}

gimp_animate_imageobject3d_preview :
  w={w} h={h}
  -_gimp_imageobject3d "_preview_",$5
  -gimp_animate_preview gimp_render3d,$w","$h",${9-18},$8",\
                                      $w","$h",${19-28},$8",0,$w,$h

#@gimp Anisotropic smoothing : gimp_animate_anisotropic_smoothing, gimp_animate_anisotropic_smoothing_preview(0)
#@gimp : Frames = _int(10,2,100)
#@gimp : Output as frames = _bool(1)
#@gimp : Output as files = _bool(0)
#@gimp : Output folder = _folder()
#@gimp : note = note{"\n<b>Global parameters :</b>"}
#@gimp : Spatial precision = float(0.8,0.1,2)
#@gimp : Angular precision = float(30,1,180)
#@gimp : Value precision = float(2,0.1,5)
#@gimp : Interpolation type = choice(0,"Nearest neighbor","Linear","Runge-Kutta")
#@gimp : Fast approximation = bool(1)
#@gimp : Iterations = int(1,1,10)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Alpha")
#@gimp : Tile subdivisions = int(1,1,10)
#@gimp : note = note{"\n<b>Starting parameters :</b>"}
#@gimp : Amplitude = float(60,0,1000)
#@gimp : Sharpness = float(0.7,0,2)
#@gimp : Anisotropy = float(0.3,0,1)
#@gimp : Gradient smoothness = float(0.6,0,10)
#@gimp : Tensor smoothness = float(1.1,0,10)
#@gimp : note = note{"\n<b>Ending parameters :</b>"}
#@gimp : Amplitude = float(60,0,1000)
#@gimp : Sharpness = float(0.7,0,2)
#@gimp : Anisotropy = float(0.3,0,1)
#@gimp : Gradient smoothness = float(0.6,0,10)
#@gimp : Tensor smoothness = float(1.1,0,10)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_animate_anisotropic_smoothing :
  -if $3 filename="$4/gmic_anisotropic_smoothing.png" -else filename="" -endif
  -animate gimp_anisotropic_smoothing,"${13-17},${5-12}",\
                                      "${18-22},${5-12}",$1,$2,@{"-quote \""$filename"\""}

gimp_animate_anisotropic_smoothing_preview :
  -gimp_animate_preview gimp_anisotropic_smoothing,"${13-17},${5-12}",\
                                                   "${18-22},${5-12}",0

#@gimp B&amp;W pencil : gimp_animate_pencilbw, gimp_animate_pencilbw_preview(0)
#@gimp : Frames = _int(10,2,100)
#@gimp : Output frames = _bool(1)
#@gimp : Output files = _bool(0)
#@gimp : Output folder = _folder()
#@gimp : note = note{"\n<b>Starting parameters :</b>"}
#@gimp : Pencil type = float(2.3,0,5)
#@gimp : Amplitude = float(100,0,200)
#@gimp : note = note{"\n<b>Ending parameters :</b>"}
#@gimp : Pencil type = float(0.3,0,5)
#@gimp : Amplitude = float(60,0,200)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_animate_pencilbw :
  -if $3 filename="$4/gmic_pencilbw.png" -else filename="" -endif
  -animate pencilbw,"${5-6}",\
                    "${7-8}",$1,$2,@{"-quote \""$filename"\""}

gimp_animate_pencilbw_preview :
  -gimp_animate_preview pencilbw,"${5-6}",\
                                 "${7-8}"

#@gimp B&amp;W stencil : gimp_animate_stencilbw, gimp_animate_stencilbw_preview(1)
#@gimp : Frames = _int(10,2,100)
#@gimp : Output frames = _bool(1)
#@gimp : Output files = _bool(0)
#@gimp : Output folder = _folder()
#@gimp : note = note{"\n<b>Starting parameters :</b>"}
#@gimp : Edge threshold = float(10,0,30)
#@gimp : Smoothness = float(10,0,30)
#@gimp : note = note{"\n<b>Ending parameters :</b>"}
#@gimp : Edge threshold = float(10,0,30)
#@gimp : Smoothness = float(20,0,30)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_animate_stencilbw :
  -if $3 filename="$4/gmic_stencilbw.png" -else filename="" -endif
  -animate stencilbw,"${5-6}",\
                     "${7-8}",$1,$2,@{"-quote \""$filename"\""}

gimp_animate_stencilbw_preview :
  -gimp_animate_preview stencilbw,"${5-6}",\
                                  "${7-8}"

#@gimp Cartoon : gimp_animate_cartoon, gimp_animate_cartoon_preview(0)
#@gimp : Frames = _int(10,2,100)
#@gimp : Output frames = _bool(1)
#@gimp : Output files = _bool(0)
#@gimp : Output folder = _folder()
#@gimp : note = note{"\n<b>Global parameters :</b>"}
#@gimp : Color quantization = int(4,2,256)
#@gimp : note = note{"\n<b>Starting parameters :</b>"}
#@gimp : Smoothness = float(0.5,0,2)
#@gimp : Sharpening = float(200,0,400)
#@gimp : Edge threshold = float(10,1,30)
#@gimp : Edge thickness = float(0.1,0,1)
#@gimp : Color strength = float(1.5,0,3)
#@gimp : note = note{"\n<b>Ending parameters :</b>"}
#@gimp : Smoothness = float(3,0,2)
#@gimp : Sharpening = float(200,0,400)
#@gimp : Edge threshold = float(10,1,30)
#@gimp : Edge thickness = float(0.1,0,1)
#@gimp : Color strength = float(1.5,0,3)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_animate_cartoon :
  -if $3 filename="$4/gmic_cartoon.png" -else filename="" -endif
  -animate cartoon,"${6-10},$5",\
                   "${11-15},$5",$1,$2,@{"-quote \""$filename"\""}

gimp_animate_cartoon_preview :
  -gimp_animate_preview cartoon,"${6-10},$5",\
                                "${11-15},$5"

#@gimp Edges : gimp_animate_edges, gimp_animate_edges_preview(0)
#@gimp : Frames = _int(10,2,100)
#@gimp : Output frames = _bool(1)
#@gimp : Output files = _bool(0)
#@gimp : Output folder = _folder()
#@gimp : note = note{"\n<b>Global parameters :</b>"}
#@gimp : Negative colors = bool(0)
#@gimp : note = note{"\n<b>Starting parameters :</b>"}
#@gimp : Smoothness = float(0,0,10)
#@gimp : Edge threshold = float(10,0,30)
#@gimp : note = note{"\n<b>Ending parameters :</b>"}
#@gimp : Smoothness = float(0,0,10)
#@gimp : Edge threshold = float(30,0,30)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_animate_edges :
  -if $3 filename="$4/gmic_edges.png" -else filename="" -endif
  -animate gimp_edges,"${6-7},$5",\
                      "${8-9},$5",$1,$2,@{"-quote \""$filename"\""}

gimp_animate_edges_preview :
  -gimp_animate_preview gimp_edges,"${6-7},$5",\
                                   "${8-9},$5"

#@gimp Edges on fire : gimp_fire_edges, gimp_fire_edges_preview(0)
#@gimp : Edges = float(0.7,0,3)
#@gimp : Attenuation = float(0.25,0,1)
#@gimp : Smoothness = float(0.5,0,5)
#@gimp : Threshold = float(25,0,100)
#@gimp : sep = separator()
#@gimp : Number of frames = _int(20,1,999)
#@gimp : Starting frame = int(20,0,199)
#@gimp : Frame skip = _int(0,0,20)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2011/07/06</i>.</small>")
gimp_fire_edges :
  -fire_edges ${1-7} -rv

gimp_fire_edges_preview :
  -gimp_split_preview "-fire_edges $1,$2,$3,$4,1,$6,0",$-1

#@gimp Lava lamp : gimp_lavalampbw, gimp_lavalampbw_preview(0)
#@gimp : Number of key-frames = _int(3,2,50)
#@gimp : Number of inter-frames = _int(30,2,100)
#@gimp : Smooth looping = _bool(1)
#@gimp : sep = separator()
#@gimp : Resolution = float(20,1,100)
#@gimp : Size = float(2,0,30)
#@gimp : Smoothness = _float(0.01,0,1)
#@gimp : Transparent background = bool(0)
gimp_lavalampbw :
  -if {!@#} (255;100^64;16^128;0) -r[-1] 512,512,1,3,3 -endif
  -repeat @# -l[$<]
    w={w} h={h}
    --r $4%,$4%,1,1,0 [-1]x{$1-1} -rand[1--1] 0,1 -stencil[1--1] $5,0
    -if $3 [1] -endif
    -morph[1--1] $2,$6,0
    -stencil[1--1] $5,0
    -r[1--1] $w,$h,1,1,3 -b[1--1] 10 -t[1--1] 50% -*[1--1] 255
    -r[1--1] 100%,100%,1,4 -j[1--1] [0] -rm[0]
    -if $3 -rm[-1] -endif
  -endl -done
  -if {!$7} -repeat @# -l[$>] -split_opacity -n[-1] 0,1 -*[0--2] [-1] -rm[-1] -endl -done -endif

gimp_lavalampbw_preview :
  -gimp_lavalampbw 2,2,1,$4,$5,$6,$7 -k[0]

#@gimp Lissajous : gimp_animate_lissajous, gimp_animate_lissajous_preview(1)
#@gimp : Frames = _int(10,2,100)
#@gimp : Output as frames = _bool(1)
#@gimp : Output as files = _bool(0)
#@gimp : Output folder = _folder()
#@gimp : sep = separator()
#@gimp : note = note{"<b>Starting parameters :</b>"}
#@gimp : Resolution = int(4096,2,8192)
#@gimp : X-size = float(0.9,0,2)
#@gimp : Y-size = float(0.9,0,2)
#@gimp : Z-size = float(3,1,10)
#@gimp : X-multiplier = float(8,0,32)
#@gimp : Y-multiplier = float(7,0,32)
#@gimp : Z-multiplier = float(0,0,32)
#@gimp : X-offset = float(0,0,1)
#@gimp : Y-offset = float(0,0,1)
#@gimp : Z-offset = float(0,0,1)
#@gimp : X-angle = float(0,0,360)
#@gimp : Y-angle = float(0,0,360)
#@gimp : Z-angle = float(0,0,360)
#@gimp : Thickness = float(0,0,50)
#@gimp : Color = color(255,255,255,255)
#@gimp : sep = separator()
#@gimp : note = note{"<b>Ending parameters :</b>"}
#@gimp : Resolution = int(4096,2,8192)
#@gimp : X-size = float(0.9,0,2)
#@gimp : Y-size = float(0.9,0,2)
#@gimp : Z-size = float(3,1,10)
#@gimp : X-multiplier = float(8,0,32)
#@gimp : Y-multiplier = float(7,0,32)
#@gimp : Z-multiplier = float(0,0,32)
#@gimp : X-offset = float(0,0,1)
#@gimp : Y-offset = float(0,0,1)
#@gimp : Z-offset = float(0,0,1)
#@gimp : X-angle = float(0,0,360)
#@gimp : Y-angle = float(0,0,360)
#@gimp : Z-angle = float(0,0,360)
#@gimp : Thickness = float(0,0,50)
#@gimp : Color = color(255,255,255,255)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2011/04/18</i>.</small>")
gimp_animate_lissajous :
  -if $3 filename="$4/gmic_lissajous.png" -else filename="" -endif
  -animate gimp_lissajous,"${5-22}",\
                          "${23-40}",$1,$2,@{"-quote \""$filename"\""}

gimp_animate_lissajous_preview :
  -gimp_animate_preview gimp_lissajous,"${5-22}",\
                                       "${23-40}",0

#@gimp Morphological filter : gimp_animate_morpho, gimp_animate_morpho_preview(0)
#@gimp : Frames = _int(10,2,100)
#@gimp : Output as frames = _bool(1)
#@gimp : Output as files = _bool(0)
#@gimp : Output folder = _folder()
#@gimp : note = note{"\n<b>Global parameters :</b>"}
#@gimp : Action = choice("Erosion","Dilation","Opening","Closing",
#@gimp : "Original - Erosion","Dilation - Original","Original - Opening","Closing - Original")
#@gimp : Invert colors = bool(false)
#@gimp : Shape = choice(0,"Square","Octagonal","Circular")
#@gimp : note = note{"\n<b>Starting parameters :</b>"}
#@gimp : Size = int(5,1,100)
#@gimp : note = note{"\n<b>Ending parameters :</b>"}
#@gimp : Size = int(50,2,100)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_animate_morpho :
  -if $3 filename="$4/gmic_morpho.png" -else filename="" -endif
  -animate gimp_morpho,"$5,$8,$6,$7,0,1",\
                       "$5,$9,$6,$7,0,1",$1,$2,@{"-quote \""$filename"\""}

gimp_animate_morpho_preview :
  -gimp_animate_preview gimp_morpho,"$5,$8,$6,$7,0,1",\
                                    "$5,$9,$6,$7,0,1"

#@gimp Polaroid : gimp_animate_polaroid, gimp_animate_polaroid_preview(1)
#@gimp : Frames = _int(10,2,100)
#@gimp : Output frames = _bool(1)
#@gimp : Output files = _bool(0)
#@gimp : Output folder = _folder()
#@gimp : note = note{"\n<b>Starting parameters :</b>"}
#@gimp : Frame size = int(10,0,400)
#@gimp : Bottom size = int(20,0,400)
#@gimp : X-shadow = float(0,-20,20)
#@gimp : Y-shadow = float(0,-20,20)
#@gimp : Smoothness = float(3,0,5)
#@gimp : Angle = float(0,-180,180)
#@gimp : Zoom = float(1,0.01,1)
#@gimp : note = note{"\n<b>Ending parameters :</b>"}
#@gimp : Frame size = int(10,0,400)
#@gimp : Bottom size = int(20,0,400)
#@gimp : X-shadow = float(0,-20,20)
#@gimp : Y-shadow = float(0,-20,20)
#@gimp : Smoothness = float(3,0,5)
#@gimp : Angle = float(20,-180,180)
#@gimp : Zoom = float(1,0.01,1)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_animate_polaroid :
  -if $3 filename="$4/gmic_polaroid.png" -else filename="" -endif
  -animate gimp_polaroid,"${5-11}",\
                         "${12-18}",$1,$2,@{"-quote \""$filename"\""}
  -r @{-max_whds},0,0,0.5,0.5

gimp_animate_polaroid_preview :
  -gimp_animate_preview gimp_polaroid,"${5-11}",\
                                      "${12-18}",0

#@gimp Rodilius : gimp_animate_rodilius, gimp_animate_rodilius_preview(1)
#@gimp : Frames = _int(10,2,100)
#@gimp : Output as frames = _bool(1)
#@gimp : Output as files = _bool(0)
#@gimp : Output folder = _folder()
#@gimp : Color mode = choice(1,"Darker","Lighter")
#@gimp : note = note{"\n<b>Starting parameters :</b>"}
#@gimp : Amplitude = float(10,0,30)
#@gimp : Thickness = float(10,0,100)
#@gimp : Sharpness = float(300,0,1000)
#@gimp : Orientations = int(5,2,20)
#@gimp : Offset = float(0,0,180)
#@gimp : note = note{"\n<b>Ending parameters :</b>"}
#@gimp : Amplitude = float(10,0,30)
#@gimp : Thickness = float(10,0,100)
#@gimp : Sharpness = float(300,0,1000)
#@gimp : Orientations = int(5,2,20)
#@gimp : Offset = float(180,0,180)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_animate_rodilius :
  -if $3 filename="$4/gmic_rodilius.png" -else filename="" -endif
  -animate rodilius,"${6-10},$5",\
                    "${11-15},$5",$1,$2,@{"-quote \""$filename"\""}

gimp_animate_rodilius_preview :
  -gimp_animate_preview rodilius,"${6-10},$5",\
                                 "${11-15},$5"

#@gimp Soft glow : gimp_animate_glow, gimp_animate_glow_preview(1)
#@gimp : Frames = _int(10,2,100)
#@gimp : Output as frames = _bool(1)
#@gimp : Output as files = _bool(0)
#@gimp : Output folder = _folder()
#@gimp : note = note{"\n<b>Starting parameters :</b>"}
#@gimp : Amplitude = float(0,0,8)
#@gimp : note = note{"\n<b>Ending parameters :</b>"}
#@gimp : Amplitude = float(3,0,8)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_animate_glow :
  -if $3 filename="$4/gmic_glow.png" -else filename="" -endif
  -animate glow,"$5",\
                "$6",$1,$2,@{"-quote \""$filename"\""}

gimp_animate_glow_preview :
  -gimp_animate_preview glow,"$5",\
                             "$6"


#@gimp _<b>Spectral handling</b>
#-------------------------------


#@gimp Fourier analysis : gimp_display_fft, gimp_display_fft(1)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_display_fft :
  -to_rgb -display_fft

#@gimp Fourier transform : gimp_fourier, gimp_fourier_preview(1)
#@gimp : Transform = choice(0,"Direct","Inverse")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_fourier :
  -if $1 -fft82float -c 0,255
  -else -float2fft8
  -endif

gimp_fourier_preview :
  -if $1 -gimp_no_preview 0
  -else -dfft
  -endif

#@gimp Fourier watermark : gimp_watermark_fourier, _none_
#@gimp : Text = text("\251 G'MIC")
#@gimp : Size = int(57,13,128)
#@gimp : sep = separator()
#@gimp : note = note("<small><b>Note : </b> To make the watermark visible afterwards, use the 'Fourier Analysis' filter. </small>")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_watermark_fourier :
  -watermark_fourier "$1",$2 -c 0,255

#@gimp Frequency merging : gimp_compose_freq, gimp_compose_freq(1)
#@gimp : Note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_compose_freq :
  -repeat {int(@#/2)}
    --[-1] 128 -*[-1] 2 -+[-2,-1] -c[-1] 0,255
  -mv[-1] 0 -done

#@gimp Frequency splitting : gimp_split_freq, gimp_split_freq_preview(1)
#@gimp : Smoothness = float(3,0,20)
#@gimp : Note = note{"<small><b>Note :</b>
#@gimp : This filter splits an image layer into two layers, one containing the low frequencies (colors), the other with the high frequencies (contours). You can thus process each layer separately, then recompose them with the previous <b>Frequency merging</b> filter.
#@gimp : </small>"}
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_split_freq_preview :
  -gimp_split_freq $1 -k[0,1] -a x

gimp_split_freq :
  -repeat @#
    --b[-1] $1 --[-2] [-1] -/[-2] 2 -+[-2] 128 -rv[-2,-1]
  -mv[-2,-1] 0 -done


#@gimp _<b>Various</b>
#----------------------

#@gimp Custom code (local) : gimp_custom_code, gimp_custom_code_preview(0)
#@gimp : Code = text(1,"-repeat @# -l[$>]\n\n  -to_rgb\n  --deform 20\n  -compose_edges 3\n\n-endl -done\n\n\n")
#@gimp : sep = separator()
#@gimp : Value range = choice("Cut","Normalize")
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator()
#@gimp : note = note{"<small><b>Note : </b>
#@gimp : This filter can execute any set of instructions understood by the <b>G'MIC</b> language interpreter.
#@gimp : Here, you can then test some commands before creating your own G'MIC custom commands and GIMP menu entries.\n\n
#@gimp : Please look at the documentation reference web page :</small>"}
#@gimp : note = link("http://gmic.sourceforge.net/reference.shtml")
#@gimp : note = note{"<small>
#@gimp : to learn more about available <b>G'MIC</b> commands.
#@gimp : </small>"}
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2011/06/14</i>.</small>")

#@gimp Custom code (global) : gimp_custom_code, gimp_custom_code_preview(1)
#@gimp : Code = text(1,"-repeat @# -l[$>]\n\n  -to_rgb\n  --deform 20\n  -compose_edges 3\n\n-endl -done\n\n\n")
#@gimp : sep = separator()
#@gimp : Value range = choice("Cut","Normalize")
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator()
#@gimp : note = note{"<small><b>Note : </b>
#@gimp : This filter can execute any set of instructions understood by the <b>G'MIC</b> language interpreter.
#@gimp : Here, you can then test some commands before creating your own G'MIC custom commands and GIMP menu entries.\n\n
#@gimp : Please look at the documentation reference web page :</small>"}
#@gimp : note = link("http://gmic.sourceforge.net/reference.shtml")
#@gimp : note = note{"<small>
#@gimp : to learn more about available <b>G'MIC</b> commands.
#@gimp : </small>"}
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2011/06/14</i>.</small>")
gimp_custom_code : -skip "${1=-skip ,}"
  -m "_gimp_custom_code_start : $1"
  -if {$3>0}
    -apply_channels "-_gimp_custom_code_start",$3,$2
  -else
    -_gimp_custom_code
    -if $2 -n 0,255 -else -c 0,255 -endif
  -endif

gimp_custom_code_preview : -skip "${1=-skip ,}"
  _gcp_arg="$1"
  -gimp_split_preview "-gimp_custom_code $_gcp_arg,${2--2}",$-1

_gimp_custom_code :
  -_gimp_custom_code_start

#@gimp Do nothing : gimp_do_nothing, gimp_do_nothing
#@gimp : note = note("<b>Note</b> : This filters does nothing on the image. Use it to manipulate layers in conjunction with the input/output options of the G'MIC plug-in.")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_do_nothing :

#@gimp GREYC Poker Tour : gimp_gpt, gimp_no_preview
#@gimp : Score type = _choice(0,"All-times","Last 50 sessions","Last 25 sessions","Last 10 sessions","Last tournament 50","Last tournament 25","Last tournament 10")
#@gimp : sep = separator(), note = note{"<b>Note</b> : This filters renders and displays the current score board for the <b>GPT (GREYC Poker Tour)</b>,
#@gimp : a small and local poker tournament organized in our research lab."};
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2011/03/27</i>.</small>")
gimp_gpt :
  -gpt ,@{-_gimp_gpt$1}

_gimp_gpt0 : -u 0
_gimp_gpt1 : -u 50
_gimp_gpt2 : -u 25
_gimp_gpt3 : -u 10
_gimp_gpt4 : -u -50
_gimp_gpt5 : -u -25
_gimp_gpt6 : -u -10

#@gimp Histogram analysis : _none_, gimp_display_histogram(1)
#@gimp : Clusters = int(256,2,256)
#@gimp : Monochrome = bool(0)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_display_histogram :
  -to_rgb -if $2 -luminance -endif
  -repeat @#
    -display_histogram[-1] {w},{h},$1,255
  -mv[-1] 0 -done

#@gimp Import data : gimp_import_image, gimp_no_preview
#@gimp : Filename = file()
#@gimp : Normalize = bool(1)
#@gimp : note = note{"\n<small><b>Note : </b>
#@gimp : This filter can import any image data read by the <b>G'MIC</b> language interpreter.
#@gimp : It includes exotic formats as : <i>Pandore, CImg, Inrimage, AVI/MPEG (requires FFMPEG installed), ...</i>
#@gimp : </small>"}
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_import_image :
  -rm -i "$1" -s z -if $2 -n 0,255 -else -c 0,255 -endif

#@gimp Quick copyright : gimp_quick_copyright, gimp_quick_copyright(0)
#@gimp : Text = text("\251 G'MIC")
#@gimp : Size = int(24,13,128)
#@gimp : Color = color(255,255,255,128)
#@gimp : Outline = int(1,0,4)
#@gimp : Position = choice(3,"Up-left","Up-right","Bottom-left","Bottom-right")
#@gimp : Offset = int(5,0,40)
#@gimp : Orientation = choice(1,"-90 deg.","0 deg.","+90 deg.","+180 deg.")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_quick_copyright :
  -i[0] 1 -text[0] "$1",0,0,$2,1,$3,$4,$5 -autocrop[0] 0 -r[0] {@{0,w}+2*$7},{@{0,h}+2*$7},1,3,0,0,0.5,0.5
  -i[1] 1 -text[1] "$1",0,0,$2,1,1 -autocrop[1] 0 -r[1] {@{1,w}+2*$7},{@{1,h}+2*$7},1,1,0,0,0.5,0.5 -dilate[1] {1+2*$7}
  -rotate[0,1] {90*($10-1)}
  -repeat {@#-2}
  -if {$8==0} -j[-1] [0],$9,$9,0,0,{$6/255},[1]
  -elif {$8==1} -j[-1] [0],{w-1-@{0,w}-$9},$9,0,0,{$6/255},[1]
  -elif {$8==2} -j[-1] [0],$9,{h-1-@{0,h}-$9},0,0,{$6/255},[1]
  -else -j[-1] [0],{w-1-@{0,w}-$9},{h-1-@{0,h}-$9},0,0,{$6/255},[1]
  -endif
  -mv[-1] 2 -done
  -rm[0,1]

#@gimp Solve maze : gimp_solve_maze, gimp_solve_maze_preview(1)
#@gimp : Starting X-coord = float(5,0,100)
#@gimp : Starting Y-coord = float(5,0,100)
#@gimp : Ending X-coord = float(95,0,100)
#@gimp : Endind Y-coord = float(95,0,100)
#@gimp : Smoothness = float(0.1,0,1)
#@gimp : Thickness = int(3,1,10)
#@gimp : Color = color(255,0,0)
#@gimp : Maze type = choice("Dark walls","White walls")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2011/09/01</i>.</small>")
gimp_solve_maze :
  -repeat @#
    --norm[-1] -t[-1] 50%
    -if {!$10} -negative[-1] -endif
    -*[-1] 255 --b[-1] $5% -*[-2] 1e10 -+[-2,-1]
    -minimal_path[-1] $1%,$2%,0,$3%,$4%,0
    -pointcloud[-1] 0 -dilate[-1] $6 -r[-1] [-2],[-2],1,1,0
    -to_rgba[-1]
    -replace_color[-1] 0,0,1,1,1,255,${7-9},255
    -replace_color[-1] 0,0,0,0,0,255,0,0,0,0
    -ellipse[-1] $1%,$2%,5,5,0,1,${7-9},255
    -ellipse[-1] $3%,$4%,5,5,0,1,${7-9},255
    -rv[-2,-1]
  -mv[-2,-1] 0 -done

gimp_solve_maze_preview :
  -drgba
  -line $1%,$2%,$3%,$4%,1,0xCCCCCCCC,${7-9}
  -ellipse $1%,$2%,3,3,0,1,${7-9}
  -ellipse $1%,$2%,3,3,0,1,0x1,0
  -ellipse $3%,$4%,3,3,0,1,${7-9}
  -ellipse $3%,$4%,3,3,0,1,0x1,0


#@gimp <b>Experimental</b>
#--------------------------

#@gimp Adjust orientation : gimp_adjust_orientation, gimp_adjust_orientation(1)
#@gimp : Threshold = float(5,0,100)
gimp_adjust_orientation :
  -repeat @#
    M={max(w,h)}
    --gradient_norm[-1] -t[-1] $1%                       # Compute binary contours.
    --*[-1] '1+y' -*[-2] '1+x' -a[-2,-1] c               # Extract contours points.
    -r[-1] {w*h},2,1,1,-1 -sort[-1] +,x -autocrop[-1] 0
    -/[-1] $M --r[-1] 1,2,1,1,2 -r[-1] [-2] --[-2,-1]    # Estimate main axis.
    --transpose[-1] -**[-2,-1]
    -eigen[-1] -rm[-2] -z[-1] 0,0
    -if {i<0} -*[-1] -1 -endif
    theta={180*atan2(i(0,1),i)/pi}
    -rm[-1]
    -if {w>h} -rotate[-1] {-$theta},0,1,50%,50%
    -else -rotate[-1] {-$theta+90},0,1,50%,50%
    -endif
  -mv[-1] 0 -done

#@gimp Anisotropic smoothing (16bits) : gimp_anisotropic_smoothing16, gimp_anisotropic_smoothing16_preview(0)
#@gimp : Input image = file()
#@gimp : Output image = text("gmic_anisotropic16.png")
#@gimp : note = note("\n<b>Filter parameters :</b>")
#@gimp : Amplitude = float(60,0,1000)
#@gimp : Sharpness = float(0.7,0,2)
#@gimp : Anisotropy = float(0.3,0,1)
#@gimp : Gradient smoothness = float(0.6,0,10)
#@gimp : Tensor smoothness = float(1.1,0,10)
#@gimp : Spatial precision = float(0.8,0.1,2)
#@gimp : Angular precision = float(30,1,180)
#@gimp : Value precision = float(2,0.1,5)
#@gimp : Interpolation = choice(0,"Nearest neighbor","Linear","Runge-Kutta")
#@gimp : Fast approximation = bool(1)
#@gimp : Iterations = int(1,1,10)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : Tiles = int(1,1,10)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_anisotropic_smoothing16 :
  -rm -i $1 -/ 256
  -gimp_anisotropic_smoothing ${3--1}
  -* 256 -if {narg($2)} -o $2 -endif -/ 256

gimp_anisotropic_smoothing16_preview :
  -i $1 -z[-1] {max(0,(w-@{-2,w})/2)},{max(0,(h-@{-2,h})/2)},{min(w-1,(w+@{-2,w})/2)},{min(h-1,(h+@{-2,h})/2)} -rm[0--2] -/ 256
  -gimp_anisotropic_smoothing ${3--1}

#@gimp Patch-based smoothing (16bits) : gimp_patch_smoothing16, gimp_patch_smoothing16_preview(0)
#@gimp : Input image = file()
#@gimp : Output image = text("gmic_patch16.png")
#@gimp : note = note("\n<b>Filter parameters :</b>")
#@gimp : Spatial variance = float(10,0.1,200)
#@gimp : Patch variance = float(10,0.1,200)
#@gimp : Patch size = int(3,2,21)
#@gimp : Lookup size = int(5,2,21)
#@gimp : Patch smoothness = float(0,0,4)
#@gimp : Fast approximation = bool(1)
#@gimp : Iterations = int(1,1,10)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_patch_smoothing16 :
  -rm -i $1 -/ 256
  -gimp_patch_smoothing ${3--1}
  -* 256 -if {narg($2)} -o $2 -endif -/ 256

gimp_patch_smoothing16_preview :
  -i $1 -z[-1] {max(0,(w-@{-2,w})/2)},{max(0,(h-@{-2,h})/2)},{min(w-1,(w+@{-2,w})/2)},{min(h-1,(h+@{-2,h})/2)} -rm[0--2] -/ 256
  -gimp_patch_smoothing ${3--1}

#@gimp Unsharp mask (16bits) : gimp_unsharp16, gimp_unsharp16_preview(0)
#@gimp : Input image = file()
#@gimp : Output image = text("gmic_unsharp16.png")
#@gimp : note = note("\n<b>Filter parameters :</b>")
#@gimp : Sharpening type = choice(0,"Gaussian","Bilateral")
#@gimp : Spatial radius = float(1.25,0,20)
#@gimp : Bilateral radius = float(30,0,60)
#@gimp : Amount = float(3,0,10)
#@gimp : Threshold = float(0,0,20)
#@gimp : Darkness level = float(1,0,4)
#@gimp : Lightness level = float(1,0,4)
#@gimp : Iterations = int(1,1,10)
#@gimp : Negative effect = bool(0)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : note = note{"\n\n<small><b>Note : </b>
#@gimp : This filter is inspired by the original <i>Unsharp Mask</i> filter in GIMP, with additional parameters.
#@gimp : </small>"}
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update : <i>2010/12/29</i>.</small>")
gimp_unsharp16 :
  -rm -i $1 -/ 256
  -gimp_unsharp ${3--1}
  -* 256 -if {narg($2)} -o $2 -endif -/ 256

gimp_unsharp16_preview :
  -i $1 -z[-1] {max(0,(w-@{-2,w})/2)},{max(0,(h-@{-2,h})/2)},{min(w-1,(w+@{-2,w})/2)},{min(h-1,(h+@{-2,h})/2)} -rm[0--2] -/ 256
  -gimp_unsharp ${3--1}

#@gimp Pink operator : gimp_pink, gimp_pink_preview(1)
#@gimp : Pink operator = choice("wshedtopo","wshedtopo inv","minima","maxima","heightminima","heightmaxima","grayskel","htkern","htkernu","lvkern","lvkernu","asf","asflin","asfr","asft","asftmed","asftndg","dilatballnum","erosballnum","lintophat")
#@gimp : Connectivity / Dir = choice("Four/x","Eight/y")
#@gimp : Smoothness = float(0,0,5)
#@gimp : Height/Rep = int(5,0,25)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : note = link("http://pinkhq.com/")
gimp_pink :
  -if   {$1==0}  -apply_channels "-b $3 -pink heightminima,{($2+1)*4},$4 -pink wshedtopo,{($2+1)*4}",$5,0
  -elif {$1==1}  -apply_channels "-b $3 -pink heightmaxima,{($2+1)*4},$4 -pink wshedtopo,{($2+1)*4},i",$5,0
  -elif {$1==2}  -apply_channels "-b $3 -pink minima,{($2+1)*4}",$5,0
  -elif {$1==3}  -apply_channels "-b $3 -pink maxima,{($2+1)*4}",$5,0
  -elif {$1==4}  -apply_channels "-b $3 -pink heightminima,{($2+1)*4},$4",$5,0
  -elif {$1==5}  -apply_channels "-b $3 -pink heightmaxima,{($2+1)*4},$4",$5,0
  -elif {$1==6}  -apply_channels "-b $3 -pink grayskel,null,4,$4",$5,0
  -elif {$1==7}  -apply_channels "-b $3 -pink htkern,null,{($2+1)*4}",$5,0
  -elif {$1==8}  -apply_channels "-b $3 -pink htkernu,null,{($2+1)*4}",$5,0
  -elif {$1==9}  -apply_channels "-b $3 -pink lvkern,null,{($2+1)*4}",$5,0
  -elif {$1==10} -apply_channels "-b $3 -pink lvkernu,null,{($2+1)*4}",$5,0
  -elif {$1==11} -apply_channels "-b $3 -pink asf,$4",$5,0
  -elif {$1==12}
     -if {$2==0} -apply_channels "-b $3 [0]x2 -a z -pink asflin,x,$4 -s z -k[-1]",$5,0
           -else -apply_channels "-b $3 [0]x2 -a z -pink asflin,y,$4 -s z -k[-1]",$5,0 -endif
  -elif {$1==13} -apply_channels "-b $3 -pink asfr,$4",$5,0
  -elif {$1==14} -apply_channels "-b $3 -pink asft,null,null,{($2+1)*4},$4",$5,0
  -elif {$1==15} -apply_channels "-b $3 -pink asftmed,{($2+1)*4},$4",$5,0
  -elif {$1==16} -apply_channels "-b $3 -pink asftndg,null,null,{($2+1)*4},$4",$5,0
  -elif {$1==17} -apply_channels "-b $3 -pink dilatballnum,$4",$5,0
  -elif {$1==18} -apply_channels "-b $3 -pink erosballnum,$4",$5,0
  -elif {$1==19} -apply_channels "-b $3 -pink lintophat,$4",$5,0
  -else          -apply_channels "-b $3 -pink heightminima,{($2+1)*4},$4 -pink wshedtopo,{($2+1)*4}",$5,0
  -endif

gimp_pink_preview :
  -gimp_split_preview "-gimp_pink ${1-5}",$6

# Local Variables:
# mode: sh
# End:
#
# (End of G'MIC custom commands)