/**
* WebGL Model Viewer - ColorMaterial.js
* Copyright © Cyril Diagne 2010.
*
* @author kikko.fr
*/

ColorMaterial = function() {
	
	this.program = null;
	
	this.shaderURL = "";
	
	this.vStr  = "attribute vec3 aVertexPosition;";
	this.vStr += "uniform mat4 uMVMatrix;";
	this.vStr += "uniform mat4 uPMatrix;";
	this.vStr += "void main(void) {";
	this.vStr += "gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);";
	this.vStr += "}";
		
	this.fStr = "uniform vec4 color;";
	this.fStr += "void main(void) {";
    this.fStr += "gl_FragColor = vec4(color.r, color.g, color.b, color.a);";
	this.fStr += "}";
	
	this.initShaderPart(this.vStr, true);
	this.initShaderPart(this.fStr, false);
	this.initMaterial();
}

ColorMaterial.prototype = {

	initShaderPart : function(shaderSrc, bIsVertex) {
		
		var shader;
				
		if (bIsVertex) {
			this.vertexShader = shader = gl.createShader(gl.VERTEX_SHADER);
		}
		else {
			this.fragmentShader = shader = gl.createShader(gl.FRAGMENT_SHADER);
		}
		
		gl.shaderSource(shader, shaderSrc);
		gl.compileShader(shader);
		
		if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
		  alert(gl.getShaderInfoLog(shader));
		}
	},
	
	
	initMaterial : function() {
	
		var program = this.program = gl.createProgram();
		gl.attachShader(program, this.vertexShader);
		gl.attachShader(program, this.fragmentShader);
		gl.linkProgram(program);
		
		if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
		  alert("Could not initialise shaders");
		}
		
		// init vertex attrib & matrix uniforms
		program.vertexPosAttrib = gl.getAttribLocation(program, "aVertexPosition");
		program.colorUniform = gl.getUniformLocation(program, "color");
		program.pMatrixUniform = gl.getUniformLocation(program, "uPMatrix");
		program.mvMatrixUniform = gl.getUniformLocation(program, "uMVMatrix");
	},
	
	setColor : function(r, g, b, a) {
		gl.uniform4f(this.program.colorUniform, r, g, b, a);
	},

	enable : function() {
	
		gl.useProgram(this.program);
		//gl.uniformMatrix4fv(this.program.pMatrixUniform, false, new WebGLFloatArray(pMatrix.flatten()));
		//gl.uniformMatrix4fv(this.program.mvMatrixUniform, false, new WebGLFloatArray(mvMatrix.flatten()));
		gl.enableVertexAttribArray(this.program.vertexPosAttrib);
	},
	
	disable : function() {	
		gl.disableVertexAttribArray(this.program.vertexPosAttrib);
	}
	
};
