package net.dzzd.extension.jogl;

import javax.media.opengl.*;
import javax.media.opengl.glu.*;
import javax.media.opengl.GL;


public class JOGLShader
{
	private String source[];	
	private int shaderId;
	private GL gl;
	private GLU glu=new GLU();
	private boolean compiled;
	private int shaderType;
	
	
		
	public JOGLShader(GL gl,int type)
	{
		this.shaderId=-1;
		this.source=null;
		this.compiled=false;
		this.gl=gl;
		this.shaderType=type;
	}
	
	public int getId()
	{
		return this.shaderId;
	}
	
	public void setSourceCode(String source[])
	{
		this.source=source;		
		this.compiled=false;	
	}
	
	protected boolean compile()
	{
		String errors;
		
		int[] lengths = { this.source[0].length() };
		
		this.shaderId = this.gl.glCreateShaderObjectARB(this.shaderType);
		
		this.gl.glShaderSourceARB(this.shaderId, this.source.length, this.source, lengths, 0);
		
		this.gl.glCompileShaderARB(this.shaderId);
		
		if ((errors = getGLError(this.gl)) != null)
			System.out.println("Shader compilation error :\n" + errors);	
			
		this.compiled=true;	
		
		return true;
	}
	
	
	private String getGLError(GL gl)
	{
		boolean hasError = false;
		String message = "";
		for (int glErr = gl.glGetError(); glErr != GL.GL_NO_ERROR; glErr = gl.glGetError())
		{
			message += (hasError ? "\n" : "") + glu.gluErrorString(glErr);
			hasError = true;
		}
		return hasError ? message : null;
	}
}