; This program is free software; you can redistribute it and/or modify
; it under the terms of the GNU General Public License as published by
; the Free Software Foundation; either version 2 of the License, or
; (at your option) any later version.
;
; This program is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
; GNU General Public License for more details.

(define (script-fu-sg-3d-ify image drawable height direction density color)
  (gimp-image-undo-group-start image)
  (let* ((height (truncate height))
         (direction (truncate (modulo (- 180 direction) 360)))
         (density (truncate density))
         (blur-layer (car (gimp-layer-copy drawable TRUE)))
         (dup-layer 0)
         (orig-sel (car (gimp-selection-save image))))
    (gimp-context-push)
    (gimp-context-set-foreground color)
    (gimp-image-add-layer image blur-layer (car (gimp-image-get-layer-position image drawable)))
    (gimp-image-lower-layer image blur-layer)
    (gimp-layer-resize-to-image-size blur-layer)
    (if (zero? (car (gimp-selection-is-empty image)))
      (begin
        (gimp-selection-invert image)
        (gimp-edit-clear blur-layer)
        (gimp-selection-invert image)
        (gimp-edit-fill blur-layer FOREGROUND-FILL)
        (gimp-selection-none image))
      (begin
        (gimp-layer-set-lock-alpha blur-layer TRUE)
        (gimp-edit-fill blur-layer FOREGROUND-FILL)
        (gimp-layer-set-lock-alpha blur-layer FALSE)))
    (plug-in-mblur RUN-NONINTERACTIVE image blur-layer 0 height direction 0 0)
    (while (> density 0)
      (set! dup-layer (car (gimp-layer-copy blur-layer TRUE)))
      (gimp-image-add-layer image dup-layer -1)
      (set! blur-layer (car (gimp-image-merge-down image dup-layer CLIP-TO-IMAGE)))
      (set! density (- density 1)))
    (gimp-drawable-set-name blur-layer "3D shadow")
    (gimp-selection-load orig-sel)
    (gimp-image-remove-channel image orig-sel)
    (gimp-context-pop)
    )
  (gimp-image-undo-group-end image)
  (gimp-progress-end)
  (gimp-displays-flush)
  )

(script-fu-register "script-fu-sg-3d-ify"
  "3D-ify"
  "3D effect per Youssef"
  "Saul Goode"
  "saulgoode"
  "Aug 2010"
  "RGB*, GRAY*"
  SF-IMAGE    "Image"    0
  SF-DRAWABLE "Drawable" 0
  SF-ADJUSTMENT "Height" '( 15 1 200 1 10 0 1)
  SF-ADJUSTMENT "Direction" '( -45 -360 360 1 10 0 1)
  SF-ADJUSTMENT "Density (1-100)" '( 10 1 100 1 10 0 1 )
  SF-COLOR "Color" '(128 128 128)
  )
(script-fu-menu-register "script-fu-sg-3d-ify"
  "<Image>/Filters/Misc"
  )
