import java.applet.*;
import java.awt.*;
import java.awt.image.*;

// display slices through the colour cube at a
// particular colour level = red + green + blue
// L. Allison, .au

public class Colour extends Applet
 { int w = 320;     // width
   int h = 320;     // height
   int level = 255; // red + green + blue

   int pix[] = new int[w*h];  // literally the memory, the pixels
   Image pixImg;


   public void init()
    { resize(w, h);
      fillPix(level);
    }


   private void fillPix(int sum) // NB. 255*3 >= sum >= 0
    {// 4-byte colour  <alpha, red, green, blue>  where alpha=translucency
      for(int i = 0; i < h; i++)
       { int lev = Math.round( (h-1-i)*255/(h-1) ); // 255 .. 0
	 int grey = (0xff << 24) | (lev << 16) | (lev << 8) | lev;
	 for(int j = 0; j < w; j++) pix[i*w+j]=grey; //clear
       }

      int Ox = Math.round(w/2),   Oy = Math.round(h/2);  // origin x,y
      int Gx =  (int)Math.round(0.4*w),
          Gy = -(int)Math.round(0.4*h*Math.tan(Math.PI/6));
      int Rx = -Gx, Ry = Gy;
      int Bx = 0, By = (int)Math.round(0.4*h/Math.cos(Math.PI/6));

//        |blue
//        |
//        +origin
//      .   .
// red.       .green

      for( int red = 0; red < 256; red++ )
       { for( int green = 0; green < 256; green++ )
	  { int blue = sum - red - green;
            if((blue >= 0) && (blue < 256))
	     { int y = Oy - Math.round( (red*Ry + green*Gy + blue*By)/255 );
	       int x = Ox + Math.round( (red*Rx + green*Gx + blue*Bx)/255 );
            // x,y is a weighted sum of the red, green, blue corners

	       if((x >= 0)&&(x < w)&&(y >= 0)&&(y < h))  // should be!
                  pix[y*w+x] = (0xff << 24)|(red << 16)|(green << 8)|blue;
       }  }  }

      pixImg = createImage(                               // an Image
		  new MemoryImageSource(w, h, pix, 0, w));// an ImageProducer
    }//fillPix


// the mouse can be used to change the colour level
   public boolean mouseDown(Event e, int xPos, int yPos)
    { level = Math.round( (h-1-yPos) * 3 * 255 / (h-1) ); // 0..3*255
      fillPix( level );
      repaint();
      return true; // mouse event handled
    }


   public void paint(Graphics g)
    { g.drawImage(pixImg, 0 /*x*/,  0 /*y*/, this /*ImageObserver*/);
      g.drawString("Lloyd Allison", 10, 15);
      g.drawString("r+g+b=" + Integer.toString(level), 10, 25);
    }
 }

// L.Allison, .au
