

#include "block.h"

#include "member.h"

#include <uniform.h>




#define GL_GLEXT_PROTOTYPES

#include <GL/glext.h>

#include <GL/gl.h> // GL 1.1 functions 

#include <GL/glx.h>

#include <stdio.h>

#include "fileSystem.h"

#include "array.h"

#include "char.h"

#include "sampler2D.h"



class uniformBlock{

	array * uniforms		= new array();

	GLint buffer;

	GLuint index;

	GLint size;

	GLchar name[64];

	GLuint bindingPoint;

	float * data;

	GLint autoUpload	= 0;

	createBuffer() {

		unsigned int uniformBufferSize	= this->size; // allocate 152 bytes of memory

		printf("create GL_UNIFORM_BUFFER of size:	%i  index:	%i \n", uniformBufferSize, this->index);

		this->data	= ( float * ) malloc( uniformBufferSize );

		glGenBuffers( 1, &this->buffer );

		glBindBuffer( GL_UNIFORM_BUFFER, this->buffer );

		glBindBufferBase( GL_UNIFORM_BUFFER, this->index, this->buffer );

		glBufferData( GL_UNIFORM_BUFFER, uniformBufferSize, 0, GL_DYNAMIC_DRAW );

		//glBufferData( GL_UNIFORM_BUFFER, uniformBufferSize, NULL, GL_DYNAMIC_DRAW ); 		

	}

	void upload() {

		//printf("upload uniform buffer:	%f 	%f  %f 	%f\n", this->data[0], this->data[1], this->data[2], this->data[3]);

		//printf("upload uniform buffer:	%i\n", this->index);

		glBindBuffer( GL_UNIFORM_BUFFER, this->buffer );

		glBindBufferBase( GL_UNIFORM_BUFFER, this->bindingPoint, this->buffer );

		glBufferData( GL_UNIFORM_BUFFER, this->size, this->data, GL_DYNAMIC_DRAW );

	}

	enableAutoUpload() {

		this->autoUpload	= 1;

	}

	void setUniform( char * name, void * value ) {

		int uniformCount 	= this->uniforms->length();

		//printf("uniformCount:		%i\n\n", uniformCount);

		for (int i = 0; i < uniformCount; ++i)
		{
			uniform * currentUniform = this->uniforms->get( i );

			char * uniformName	= (char *) currentUniform->name;

			if( uniformName == name ) {

				//printf("\n\n Update this uniform  from uniform block %s\n\n", name);

				switch( currentUniform->type ) {

					case GL_FLOAT_VEC2:

						vector2 * vector2Value	= ( vector2 * ) value;

						GLuint size			= 8;

						GLint offset		= currentUniform->offset;


						if( this->autoUpload ) {

							float data[2]	= { vector2Value->x, vector2Value->y };


							glBindBuffer( GL_UNIFORM_BUFFER, this->buffer );

							glBindBufferBase( GL_UNIFORM_BUFFER, 0, this->buffer );

						//	glBufferData( GL_UNIFORM_BUFFER, 16, data2, GL_DYNAMIC_DRAW );

							glBufferSubData( GL_UNIFORM_BUFFER, offset, size, data );

							//printf("using autoUpload	%i  %i %f %f\n", offset, size, data[0], data[1]);

						} else {

							GLint dataOffset	= offset / sizeof( float );

							this->data[ dataOffset ] = vector2Value->x;

							this->data[ dataOffset + 1 ] = vector2Value->y;

						}

					break;

					case GL_FLOAT_VEC3:

						vector3 * vector3Value	= ( vector3 * ) value;

						

					break;

					case GL_SAMPLER_2D:

	
					break;

				}

			}


		}


	}

}