/// Evolver Copyright 2000, Morgan McGuire
/// matrix@alum.mit.edu   http://graphics3d.com/matrix
import java.awt.*;

public final class VGradient extends ZeroArgumentOperator implements ELOperator 
{
  static float coeff[];
  static {
    coeff = new float[128];
    for(int x = 0; x < 128; x++) {
      coeff[x] = 2.0f * (x / 127.0f) - 1.0f;
    }
  }

  public void apply(ELMatrix argument[], ELMatrix out, ELEnvironment environment)
  {
    checkArguments(argument);
    
    // For extra performance, pull the arrays into locals so we avoid
    // excess dereferences.
    float red[] = out.red;
    float grn[] = out.grn;
    float blu[] = out.blu;

    int width = out.getWidth();
    int height = out.getHeight();
    float span = height - 1;

    if ((width == 128) && (height == 128)) {
      final float coeff[] = this.coeff;
      for(int y = 127; y >= 0; y--) {
        float value = coeff[y];
        int i = (y << 7) + 127;
        for(int x = 127; x >= 0; x--) {
          red[i] = value;
          grn[i] = value;
          blu[i] = value;
          i--;
        }      
      }
    } else {
      for(int y = height - 1; y >= 0; y--) {
        float value = 1.0f - 2.0f * (y / span);
        int i = y * width + (width - 1);
        for(int x = width - 1; x >= 0; x--) {
          red[i] = value;
          grn[i] = value;
          blu[i] = value;
        i--;
        }      
      }
    }
  }

  public String name()
  {
    return "VGradient";
  }

  public String description()
  {
    return "A vertical gradient from -1 to 1";
  }  

  public void paintIcon(Graphics2D graphics, int x, int y, int width, int height)
  {
    graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
    for(int yy = 0; yy < height; yy++) {
      float v = yy / (float)(height - 1);
      graphics.setColor(new Color(v, v, v, 1.0f - v));
      graphics.drawLine(x, y + yy, x + width, y + yy);
    }
  }
}
