/*
* This file is part of 3DzzD http://dzzd.net/.
*
* Released under LGPL
*
* 3DzzD is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* 3DzzD is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 3DzzD.  If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2005 - 2009 Bruno Augier
*/

package net.dzzd.core;

import java.awt.image.PixelGrabber;

import net.dzzd.access.*;
import net.dzzd.utils.Log;
import java.awt.Toolkit;
import java.net.*;
import java.awt.image.*;


/** 
 *  Class to manage ImageTexture
 *
 *  @version 1.0
 *  @since 1.0
 *  @author Bruno Augier
 *
 *  Copyright Bruno Augier 2005 
 */


import java.awt.Image;



public class ImageTexture extends Texture implements IImageTexture
{
	public static final long serialVersionUID = 0x00000001;
	protected Image image;		//Source picture
	
	public ImageTexture()
	{
		super();
		this.image=null;
	}
	
	public ImageTexture(Image image)
	{
		this();
		this.setImage(image);
	}

	public void build()
	{
		super.build();
	}
	
	public void setImage(Image image)
	{
		this.image=image;
		this.resizeImageToTexture();
		this.imageToTexturePixels();
		//Log.log("width="+this.width);
		//Log.log("height="+this.height);
		//Log.log("maskWidth="+this.maskWidth);
		//Log.log("maskHeight="+this.maskHeight);
		//Log.log("decalWidth="+this.decalWidth);
		//Log.log("decalHeight="+this.decalHeight);

	}
	
    private void resizeImageToTexture()
	{
		int w=this.image.getWidth(null);
		int h=this.image.getHeight(null);
		this.setSize(w,h);
		
		//SCALL with & height to nearest power of two
		if(w!=this.width || h!=this.height)		
		{
			Image i=this.image.getScaledInstance(this.width,this.height,Image.SCALE_SMOOTH);
			this.image = i;
		}
	}

   private void imageToTexturePixels()
   {
		this.pixels=new int[this.width*this.height];
		PixelGrabber pg= new PixelGrabber(this.image,0,0,this.width,this.height,this.pixels,0,this.width);
    	try 
    	{
    		pg.grabPixels();
    	} 
    	catch (InterruptedException ie) 
    	{
    		ie.printStackTrace();
    	}
    	
    	int p0=this.pixels[0]&0xFF000000;
    	for(int n=1;n<this.pixels.length;n++)    	
    		if((this.pixels[n]&0xFF000000) != p0)
    			this.setAlphaChannelEnabled(true);
    	
    		    		
    	this.image.flush();
		this.image=null;
		System.gc();
	}      
}
