package com.xith.client.landscape.brushes;

import java.awt.*;
import java.awt.image.*;
import java.awt.color.*;

/**
 * <p>Manager for a greyscale alpha mask which can be used to blend
 * bitmaps onto a surface.</p>
 * <p> </p>
 * <p> Copyright (c) 2000-2002, David J. Yazel</p>
 * <p> Teseract Software, LLP</p>
 * @author David Yazel
 *
 */

public class AlphaMask {

   byte[] mask;
   int dim;

   public AlphaMask(int dim) {
      mask = new byte[dim*dim];
      this.dim = dim;
   }

   public void set(int x, int y, float value) {
      mask[x*dim+y] = (byte)(255 * value);
   }

   public void set(int x, int y, int value) {
         mask[x*dim+y] = (byte)(0xff & value);
      }

   public byte getByte(int x, int y) {
      return mask[x*dim+y];
   }

   public int getInt(int x, int y) {
      return (0xff & mask[x*dim+y]);
   }

   public int getShiftedInt( int x, int y) {
      return ((0xff & mask[x*dim+y]) << 24);
   }

   public void makeOpaque() {
      for (int i=0;i<dim;i++)
         for (int j=0;j<dim;j++)
            mask[i*dim+j] = (byte)0xff;

   }
   /**
    * This method will apply the specified mask to this mask.  Simply put it
    * will set each mask pixel to the smaller of the two.  This way we can force
    * the blend of one mask to obey the blend of the other.
    * @param m
    */
   public void maskMask( AlphaMask m ) {

      for (int i=0;i<dim;i++)
         for (int j=0;j<dim;j++) {
            int v1 = getInt(i,j);
            int v2 = m.getInt(i,j);
            if (v2<v1) set(i,j,v2);
         }

   }

   /**
    * returns a grey scaled buffered image which is used for a splat mask
    * @return
    */
   public BufferedImage getImage() {

      ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
      int[] nBits = {8};
      ColorModel cm = new ComponentColorModel(cs, nBits, false, false,
                     Transparency.OPAQUE, 0);
      int[] bandOffset = {0};

      DataBufferByte buffer = new DataBufferByte(mask,dim*dim);

      WritableRaster newRaster =
        Raster.createInterleavedRaster(buffer, dim, dim, dim, 1, bandOffset, null);

      BufferedImage newImage = new BufferedImage(cm, newRaster, false, null);
      return newImage;

   }


}