#!/usr/bin/perl

# sent to me by Seth Burgess <sjburges@gimp.org>
# small changes my Marc Lehmann <pcg@goof.com>
# 2014/03/17 ported to GIMP 2.8.10 by Ed J:
#   - I think the fill with the foreground colour should be background
#     since that's the colour expressly set, but didn't touch
#   - adjusted the maths so inputs are in degrees

# There's corruption on the edges of this in smear mode.  Yuck.

use Gimp qw(:auto N_ __);
use Gimp::Fu;

#Gimp::set_trace(TRACE_CALL);

sub windify {
	my ($img, $drawable, $angle, $density, $distance, $wrap) = @_;
	gimp_context_push();
	my $xsize = gimp_drawable_width($drawable);
	my $ysize = gimp_drawable_height($drawable);

	my $out = gimp_image_new($xsize,$ysize,0);
	gimp_context_set_background([128,128,128]);
	my $windlayer = gimp_layer_new($out,$xsize,$ysize,RGB_IMAGE,"Windlayer",100,NORMAL_MODE);
	gimp_drawable_fill($windlayer, 0);
	gimp_image_insert_layer($out,$windlayer,0,0);
	my $windlayercopy = gimp_layer_copy($windlayer, 1);
	gimp_image_insert_layer($out,$windlayercopy,0,0);
	plug_in_noisify($out,$windlayercopy,0,$density/255,
                                                $density/255,
                                                $density/255,1);

	plug_in_mblur($out,$windlayercopy,
                     0,  #0=linear
                     15, #length
                     $angle,
                     gimp_drawable_width($windlayercopy)/2,
                     gimp_drawable_height($windlayercopy)/2
                     );
	gimp_layer_set_mode($windlayercopy, 10); # Lighten Only
	gimp_image_merge_visible_layers($out,0);

# many thanks to Dov for this suggestion as a workaround to the
# gimp_image_merge_visible_layers bug

	my $newlay = gimp_image_get_active_layer ($out);
        my $xmult = cos(3.14159*$angle/180);
        my $ymult = sin(3.14159*$angle/180);

	plug_in_displace($img,$drawable,-$distance*$xmult,
                                          $distance*$ymult,
					  1,1, $newlay,$newlay, $wrap);
        gimp_drawable_offset($drawable,1,0,$distance*$xmult,-$distance*$ymult);
	gimp_image_delete ($out);
	gimp_displays_flush();
        gimp_context_pop();

	();
	}

register
	"windify",
	"Add wind to an image",
	"Blow your image all over :)",
	"Seth Burgess",
	"Seth Burgess <sjburges\@gimp.org>",
	"1998-09-14",
	N_"<Image>/Filters/Distorts/Windify...",
	"*",
	[
	 [PF_INT32, "angle", "Wind Angle in degrees, 0 is right, increases anticlockwise", 120],
	 [PF_INT32, "density", "How Much Is Blown",80],
	 [PF_VALUE, "distance", "How Far It's Blown",30],
	 [PF_TOGGLE, "wrap", "Smear on Edges (or Wrap)",1]
	],
	\&windify;

exit main;

=head1 LICENSE

Copyright Seth Burgess.
Distributed under the same terms as Gimp-Perl.

=cut
