import java.io.*; 
import java.util.*;
import java.awt.*;
import java.math.*;

/**
 * Title:        WaterMixApplet
 * Description:  Mixing water with Fuzzy Logic
 * Copyright:    Copyright (c) 2001
 * @author S. Robl <stefan@qdev.de>, A. Heinze <mail@aheinze.de>
 * @version 1.0
 */

public class WaterDrops
{
	private static int pixelsize=3;
    
    private Random random=new Random();
    private float xx[], yy[], ystep;
    private int sx, sy, leftx, rightx, bottomy, height;
    private float pressure;
    private int dither, count;
    private boolean leftright;
	private Color watercolor;
    
	// ****************************************************************
      
    public WaterDrops() 
	{
    }
    
    /*
    initalizes especially coordinates of the water environment  
      
    leftright: false: right / true: left
    sx,sy    : water start point
    leftx    : left water border
    rightx   : right water border
    bottomy  : bottom water border
    dither   : specifies, how much the water disperses
    pressure : specifies the amount of pressure, the water is sprayed
    */
    public void initValues(boolean leftright, int sx, int sy, int leftx, int rightx, int bottomy, int dither, float pressure, int numberOfSteps)
    {
      this.sx=sx;
      this.sy=sy;
      this.leftx=leftx;
      this.rightx=rightx-pixelsize-1;
      this.bottomy=bottomy-pixelsize-1;
      if (dither<1)
        dither=1;
      this.dither=dither;
      this.pressure=pressure;
      this.leftright=leftright;
      
      height=bottomy-sy;
      ystep=((float) height/(float) numberOfSteps)*2;
    }
    
    // call this before you restart animation!
    // count: number of waterdrops
    // color: color of water
    public void initAnimation(int count, Color color)
    {
      int h=height/2;

      this.count=count;
      xx=new float [count];
      yy=new float [count];
      watercolor=color;
      
      for(int i=0; i<count; i++)
      {
        xx[i]=sx;
        yy[i]=sy+((random.nextInt()%h)-h);
      }
    }
    
    
    // do one animation step
    public void animate(Graphics g)
    {
      g.setColor(watercolor);
      
      float x, y, h;
      
      for(int i=0; i<count; i++)
      {
        x=xx[i];
        y=yy[i];
      
        if (y>sy-ystep && y<bottomy)
        {
          if (y<sy)
            y=sy;
        
          g.fillRect((int) x, (int) y, pixelsize, pixelsize);
          
          h=(y-sy+1);
        
          float p=0;
          
          if (h<(5*ystep))
            p+=(float) ((random.nextInt()%(((dither*3)/5)+1))+dither);
          
          p+=(float) Math.pow(3, ((height-h)*3)/height)*pressure;
          
          if (leftright)
          {
            x+=p;
            if (x>rightx)
              x=rightx;
          }
          else
          {
            x-=p;
            if (x<leftx)
              x=leftx;
          }
        }
        
        xx[i]=x;
        yy[i]=y+ystep;
      }
    }
}
