bool initProgram()
	{
		bool Validated = true;
	
		std::array<GLuint, shader::MAX> ShaderName;
		
		compiler Compiler;
		ShaderName[shader::VERT_TRANSFORM] = Compiler.create(GL_VERTEX_SHADER, getDataDirectory() + VERT_SHADER_SOURCE_TRANSFORM, "--version 150 --profile core");
		ShaderName[shader::VERT_FEEDBACK] = Compiler.create(GL_VERTEX_SHADER, getDataDirectory() + VERT_SHADER_SOURCE_FEEDBACK, "--version 150 --profile core");
		ShaderName[shader::FRAG_FEEDBACK] = Compiler.create(GL_FRAGMENT_SHADER, getDataDirectory() + FRAG_SHADER_SOURCE_FEEDBACK, "--version 150 --profile core");
		Validated = Validated && Compiler.check();

		if(Validated)
		{
			ProgramName[program::TRANSFORM] = glCreateProgram();
			glAttachShader(ProgramName[program::TRANSFORM], ShaderName[shader::VERT_TRANSFORM]);
			glBindAttribLocation(ProgramName[program::TRANSFORM], semantic::attr::POSITION, "Position");

			GLchar const * Strings[] = {"gl_Position", "block.Color"}; 
			glTransformFeedbackVaryings(ProgramName[program::TRANSFORM], 2, Strings, GL_INTERLEAVED_ATTRIBS); 
			glLinkProgram(ProgramName[program::TRANSFORM]);

			Validated = Validated && Compiler.check_program(ProgramName[program::TRANSFORM]);

			char Name[64];
			memset(Name, 0, 64);
			GLsizei Length(0);
			GLsizei Size(0);
			GLenum Type(0);

			glGetTransformFeedbackVarying(
				ProgramName[program::TRANSFORM],
				0,
				64,
				&Length,
				&Size,
				&Type,
				Name);

			Validated = Validated && (Size == 1) && (Type == GL_FLOAT_VEC4);
		}

		// Get variables locations
		if(Validated)
		{
			TransformUniformMVP = glGetUniformLocation(ProgramName[program::TRANSFORM], "MVP");

			GLint ActiveUniforms(0);
			glGetProgramiv(ProgramName[program::TRANSFORM], GL_ACTIVE_UNIFORMS, &ActiveUniforms);

			char Name[64];
			memset(Name, 0, 64);
			GLsizei Length(0);
			GLsizei Size(0);
			GLenum Type(0);

			for(GLint i = 0; i < ActiveUniforms; ++i)
			{
				glGetActiveUniform(
					ProgramName[program::TRANSFORM],
					i,
					64,
					&Length,
					&Size,
					&Type,
					Name);

				GLint Location = glGetUniformLocation(ProgramName[program::TRANSFORM], Name);

				if(TransformUniformMVP == Location)
				{
					Validated = Validated && (Size == 1) && (Type == GL_FLOAT_MAT4);
					Validated = Validated && (TransformUniformMVP >= 0);
				}
			}
		}

		// Create program
		if(Validated)
		{
			ProgramName[program::FEEDBACK] = glCreateProgram();
			glAttachShader(ProgramName[program::FEEDBACK], ShaderName[shader::VERT_FEEDBACK]);
			glAttachShader(ProgramName[program::FEEDBACK], ShaderName[shader::FRAG_FEEDBACK]);

			glBindAttribLocation(ProgramName[program::FEEDBACK], semantic::attr::POSITION, "Position");
			glBindAttribLocation(ProgramName[program::FEEDBACK], semantic::attr::COLOR, "Color");
			glBindFragDataLocation(ProgramName[program::FEEDBACK], semantic::frag::COLOR, "Color");
			glLinkProgram(ProgramName[program::FEEDBACK]);
			Validated = Validated && Compiler.check_program(ProgramName[program::FEEDBACK]);
		}

		return Validated && this->checkError("initProgram");
	}
Exemplo n.º 2
0
bool CShader::Compile()
{
	tstring sShaderHeader = CShaderLibrary::GetShaderHeader();

	if (CShaderLibrary::Get()->m_iSamples)
		sShaderHeader += "#define USE_MULTISAMPLE_TEXTURES 1\n";

	sShaderHeader += CShaderLibrary::GetShaderFunctions();

	FILE* f = tfopen("shaders/" + m_sVertexFile + ".vs", "r");

	TAssert(f);
	if (!f)
		return false;

	tstring sVertexShader = sShaderHeader;
	sVertexShader += "uniform mat4x4 mProjection;\n";
	sVertexShader += "uniform mat4x4 mView;\n";
	sVertexShader += "uniform mat4x4 mGlobal;\n";

	tstring sLine;
	while (fgetts(sLine, f))
		sVertexShader += sLine;

	fclose(f);

	f = tfopen("shaders/" + m_sFragmentFile + ".fs", "r");

	TAssert(f);
	if (!f)
		return false;

	tstring sFragmentShader = sShaderHeader;
	sFragmentShader += "out vec4 vecOutputColor;\n";

	while (fgetts(sLine, f))
		sFragmentShader += sLine;

	fclose(f);

	size_t iVShader = glCreateShader(GL_VERTEX_SHADER);
	const char* pszStr = sVertexShader.c_str();
	glShaderSource((GLuint)iVShader, 1, &pszStr, NULL);
	glCompileShader((GLuint)iVShader);

	int iVertexCompiled;
	glGetShaderiv((GLuint)iVShader, GL_COMPILE_STATUS, &iVertexCompiled);

	if (iVertexCompiled != GL_TRUE || Application()->HasCommandLineSwitch("--debug-gl"))
	{
		int iLogLength = 0;
		char szLog[1024];
		glGetShaderInfoLog((GLuint)iVShader, 1024, &iLogLength, szLog);
		CShaderLibrary::Get()->WriteLog(m_sVertexFile + ".vs", szLog, pszStr);
	}

	size_t iFShader = glCreateShader(GL_FRAGMENT_SHADER);
	pszStr = sFragmentShader.c_str();
	glShaderSource((GLuint)iFShader, 1, &pszStr, NULL);
	glCompileShader((GLuint)iFShader);

	int iFragmentCompiled;
	glGetShaderiv((GLuint)iFShader, GL_COMPILE_STATUS, &iFragmentCompiled);

	if (iFragmentCompiled != GL_TRUE || Application()->HasCommandLineSwitch("--debug-gl"))
	{
		int iLogLength = 0;
		char szLog[1024];
		glGetShaderInfoLog((GLuint)iFShader, 1024, &iLogLength, szLog);
		CShaderLibrary::Get()->WriteLog(m_sFragmentFile + ".fs", szLog, pszStr);
	}

	size_t iProgram = glCreateProgram();

	glBindAttribLocation(iProgram, 0, "vecPosition");		// Force position at location 0. ATI cards won't work without this.

	glAttachShader((GLuint)iProgram, (GLuint)iVShader);
	glAttachShader((GLuint)iProgram, (GLuint)iFShader);
	glLinkProgram((GLuint)iProgram);

	int iProgramLinked;
	glGetProgramiv((GLuint)iProgram, GL_LINK_STATUS, &iProgramLinked);

	if (iProgramLinked != GL_TRUE || Application()->HasCommandLineSwitch("--debug-gl"))
	{
		int iLogLength = 0;
		char szLog[1024];
		glGetProgramInfoLog((GLuint)iProgram, 1024, &iLogLength, szLog);
		CShaderLibrary::Get()->WriteLog("link", szLog, "link");
	}

	if (iVertexCompiled != GL_TRUE || iFragmentCompiled != GL_TRUE || iProgramLinked != GL_TRUE)
	{
		TError("Shader compilation failed for shader " + m_sName + ". Check shaders.txt\n");

		Destroy();

		return false;
	}

	m_iProgram = iProgram;
	m_iVShader = iVShader;
	m_iFShader = iFShader;

	m_iPositionAttribute = glGetAttribLocation(m_iProgram, "vecPosition");
	m_iNormalAttribute = glGetAttribLocation(m_iProgram, "vecNormal");
	m_iTangentAttribute = glGetAttribLocation(m_iProgram, "vecTangent");
	m_iBitangentAttribute = glGetAttribLocation(m_iProgram, "vecBitangent");
	for (size_t i = 0; i < MAX_TEXTURE_CHANNELS; i++)
		m_aiTexCoordAttributes[i] = glGetAttribLocation(m_iProgram, sprintf("vecTexCoord%d", i).c_str());
	m_iColorAttribute = glGetAttribLocation(m_iProgram, "vecVertexColor");

	glBindFragDataLocation(m_iProgram, 0, "vecOutputColor");

	TAssert(m_iPositionAttribute != ~0);

	int iNumUniforms;
	glGetProgramiv(m_iProgram, GL_ACTIVE_UNIFORMS, &iNumUniforms);

	char szUniformName[256];
	GLsizei iLength;
	GLint iSize;
	GLenum iType;
	for (int i = 0; i < iNumUniforms; i++)
	{
		glGetActiveUniform(m_iProgram, i, sizeof(szUniformName), &iLength, &iSize, &iType, szUniformName);

		tstring sUniformName = szUniformName;
		if (sUniformName == "mProjection")
			continue;
		if (sUniformName == "mView")
			continue;
		if (sUniformName == "mGlobal")
			continue;

		CShader::CUniform& oUniform = m_asUniforms[sUniformName];
		oUniform.m_pDefault = nullptr;
		switch (iType)
		{
		case GL_FLOAT: oUniform.m_sUniformType = "float"; break;
		case GL_FLOAT_VEC2: oUniform.m_sUniformType = "vec2"; break;
		case GL_FLOAT_VEC3: oUniform.m_sUniformType = "vec3"; break;
		case GL_FLOAT_VEC4: oUniform.m_sUniformType = "vec4"; break;
		case GL_INT: oUniform.m_sUniformType = "int"; break;
		case GL_BOOL: oUniform.m_sUniformType = "bool"; break;
		case GL_FLOAT_MAT4: oUniform.m_sUniformType = "mat4"; break;
		case GL_SAMPLER_2D: oUniform.m_sUniformType = "sampler2D"; break;
		default: TUnimplemented();
		}
	}

	for (auto it = m_aParameters.begin(); it != m_aParameters.end(); it++)
	{
		for (size_t j = 0; j < it->second.m_aActions.size(); j++)
		{
			auto it2 = m_asUniforms.find(it->second.m_aActions[j].m_sName);
			TAssert(it2 != m_asUniforms.end());
			if (it2 == m_asUniforms.end())
			{
				TError("Shader '" + m_sName + "' specifies a uniform '" + it->second.m_aActions[j].m_sName + "' that is not in the linked program.\n");
				continue;
			}

			CShader::CUniform& oUniform = it2->second;

			// This is almost cheating
			CData d;
			d.SetValue(it->second.m_aActions[j].m_sValue);

			if (oUniform.m_sUniformType == "float")
				it->second.m_aActions[j].m_flValue = d.GetValueFloat();
			else if (oUniform.m_sUniformType == "vec2")
				it->second.m_aActions[j].m_vec2Value = d.GetValueVector2D();
			else if (oUniform.m_sUniformType == "vec3")
				it->second.m_aActions[j].m_vecValue = d.GetValueVector();
			else if (oUniform.m_sUniformType == "vec4")
				it->second.m_aActions[j].m_vec4Value = d.GetValueVector4D();
			else if (oUniform.m_sUniformType == "int")
				it->second.m_aActions[j].m_iValue = d.GetValueInt();
			else if (oUniform.m_sUniformType == "bool")
				it->second.m_aActions[j].m_bValue = d.GetValueBool();
			else if (oUniform.m_sUniformType == "mat4")
			{
				TUnimplemented();
			}
			else if (oUniform.m_sUniformType == "sampler2D")
			{
				// No op.
			}
			else
				TUnimplemented();
		}
	}

	for (auto it = m_aDefaults.begin(); it != m_aDefaults.end(); it++)
	{
		auto it2 = m_asUniforms.find(it->first);
		TAssert(it2 != m_asUniforms.end());
		if (it2 == m_asUniforms.end())
		{
			TError("Shader '" + m_sName + "' specifies a default for uniform '" + it->second.m_sName + "' that is not in the linked program.\n");
			continue;
		}

		CShader::CUniform& oUniform = it2->second;
		oUniform.m_pDefault = &it->second;

		// Again with the cheating.
		CData d;
		d.SetValue(it->second.m_sValue);

		if (oUniform.m_sUniformType == "float")
			it->second.m_flValue = d.GetValueFloat();
		else if (oUniform.m_sUniformType == "vec2")
			it->second.m_vec2Value = d.GetValueVector2D();
		else if (oUniform.m_sUniformType == "vec3")
			it->second.m_vecValue = d.GetValueVector();
		else if (oUniform.m_sUniformType == "vec4")
			it->second.m_vec4Value = d.GetValueVector4D();
		else if (oUniform.m_sUniformType == "int")
			it->second.m_iValue = d.GetValueInt();
		else if (oUniform.m_sUniformType == "bool")
			it->second.m_bValue = d.GetValueBool();
		else if (oUniform.m_sUniformType == "mat4")
		{
			TUnimplemented(); 
		}
		else if (oUniform.m_sUniformType == "sampler2D")
		{
			TUnimplemented(); // Can't set a default texture... yet.
		}
		else
			TUnimplemented();
	}

	return true;
}
Exemplo n.º 3
0
// Create a GLSL program object from vertex and fragment shader files (in C)
GLuint InitShader(const char* vShaderFile, const char* fShaderFile)
{
	struct Shader {
		const char*  filename;
		GLenum       type;
		GLchar*      source;
	}  shaders[2] = {
		{ vShaderFile, GL_VERTEX_SHADER, NULL },
		{ fShaderFile, GL_FRAGMENT_SHADER, NULL }
	};

	GLuint program = glCreateProgram();

	for ( int i = 0; i < 2; ++i ) {
		Shader& s = shaders[i];
		s.source = readShaderSource( s.filename );
		if ( shaders[i].source == NULL ) {
			std::cerr << "Failed to read " << s.filename << std::endl;
			exit( EXIT_FAILURE );
		}

		GLuint shader = glCreateShader( s.type );
		glShaderSource( shader, 1, (const GLchar**) &s.source, NULL );
		glCompileShader( shader );

		GLint  compiled;
		glGetShaderiv( shader, GL_COMPILE_STATUS, &compiled );
		if ( !compiled ) {
			std::cerr << s.filename << " failed to compile:" << std::endl;
			GLint  logSize;
			glGetShaderiv( shader, GL_INFO_LOG_LENGTH, &logSize );
			char* logMsg = new char[logSize];
			glGetShaderInfoLog( shader, logSize, NULL, logMsg );
			std::cerr << logMsg << std::endl;
			delete [] logMsg;

			exit( EXIT_FAILURE );
		}

		delete [] s.source;

		glAttachShader( program, shader );
	}

	/* link  and error check */
	glLinkProgram(program);

	GLint  linked;
	glGetProgramiv( program, GL_LINK_STATUS, &linked );
	if ( !linked ) {
		std::cerr << "Shader program failed to link" << std::endl;
		GLint  logSize;
		glGetProgramiv( program, GL_INFO_LOG_LENGTH, &logSize);
		char* logMsg = new char[logSize];
		glGetProgramInfoLog( program, logSize, NULL, logMsg );
		std::cerr << logMsg << std::endl;
		delete [] logMsg;

		exit( EXIT_FAILURE );
	}

	/* use program object */
	//   glUseProgram(program);

	return program;
}
Exemplo n.º 4
0
void ShaderProgram::attach(Shader shader) {
    glAttachShader(this->program, shader.getId());
}
GLuint
LoadShaders(ShaderInfo *shaders) {
	if (shaders == NULL) {
		return 0;
	}

	GLuint program = glCreateProgram();

	ShaderInfo *entry = shaders;
	while (entry->type != GL_NONE) {
		GLuint shader = glCreateShader(entry->type);

		entry->shader = shader;

		const GLchar *source = ReadShader(entry->filename);
		if (source == NULL) {
			for (entry = shaders; entry->type != GL_NONE; ++entry) {
				glDeleteShader(entry->shader);
				entry->shader = 0;
			}

			return 0;
		}

		glShaderSource(shader, 1, &source, NULL);
		delete[] source;

		glCompileShader(shader);

		GLint compiled;
		glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled);
		if (!compiled) {
#ifdef _DEBUG
			GLsizei len;
			glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &len);

			GLchar* log = new GLchar[len + 1];
			glGetShaderInfoLog(shader, len, &len, log);
			std::cerr << "Shader compilation failed: " << log << std::endl;
			delete [] log;
#endif /* DEBUG */

			return 0;
		}

		glAttachShader(program, shader);

		++entry;
	}

#ifdef GL_VERSION_4_1
	if (GLEW_VERSION_4_1) {
		// glProgramParameteri( program, GL_PROGRAM_SEPARABLE, GL_TRUE );
	}
#endif /* GL_VERSION_4_1 */

	glLinkProgram(program);

	GLint linked;
	glGetProgramiv(program, GL_LINK_STATUS, &linked);
	if (!linked) {
#ifdef _DEBUG
		GLsizei len;
		glGetProgramiv(program, GL_INFO_LOG_LENGTH, &len);

		GLchar* log = new GLchar[len + 1];
		glGetProgramInfoLog(program, len, &len, log);
		std::cerr << "Shader linking failed: " << log << std::endl;
		delete [] log;
#endif /* DEBUG */

		for (entry = shaders; entry->type != GL_NONE; ++entry) {
			glDeleteShader(entry->shader);
			entry->shader = 0;
		}

		return 0;
	}

	return program;
}
Exemplo n.º 6
0
int main() {
    //    createWindow & context
    if (!glfwInit()) {
        fprintf(stderr, "Failed to initialize GLFW\n");
        return -1;
    }
    glfwWindowHint(GLFW_SAMPLES, 4); // 4x antialiasing
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

    // Open a window and create its OpenGL context
    GLFWwindow *window = glfwCreateWindow(800, 600, "OpenGL", nullptr, nullptr); // Windowed
    glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);
    if (window == NULL){
        fprintf(stderr, "Failed to open GLFW window\n");
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);

//// GLEW

    // Initialize GLEW
    glewExperimental = true;
    GLenum err = glewInit();
    if (GLEW_OK != err) {
        /* Problem: glewInit failed, something is seriously wrong. */
        fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
    }
    fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));


    // Create Vertex Array Object
    GLuint vao;
    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);

    // Create a Vertex Buffer Object and copy the vertex data to it
    GLuint vbo;
    glGenBuffers(1, &vbo);

    GLfloat vertices[] = {
            -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, // Top-left
            0.5f, 0.5f, 0.0f, 1.0f, 0.0f, // Top-right
            0.5f, -0.5f, 0.0f, 0.0f, 1.0f, // Bottom-right
            -0.5f, -0.5f, 1.0f, 1.0f, 1.0f  // Bottom-left
    };

//    GLfloat vertices[] = {
//            0.0f,  0.5f, 1.0f, 0.0f, 0.0f,
//            0.5f, -0.5f, 0.0f, 1.0f, 0.0f,
//            -0.5f, -0.5f, 0.0f, 0.0f, 1.0f
//    };

//    GLfloat vertices[] = {
//            0.0f,  0.5f, 0.0f,
//            0.5f, -0.5f, 0.5f,
//            -0.5f, -0.5f, 1.0f
//    };

    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    // Create an element array
    GLuint ebo;
    glGenBuffers(1, &ebo);

    GLuint elements[] = {
            0, 1, 2,
            1, 2, 3,
    };

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elements), elements, GL_STATIC_DRAW);

    // Create and compile the vertex shader
    GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vertexShader, 1, &vertexSource, NULL);
    glCompileShader(vertexShader);

    // Create and compile the fragment shader
    GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragmentShader, 1, &fragmentSource, NULL);
    glCompileShader(fragmentShader);

    // Link the vertex and fragment shader into a shader program
    GLuint shaderProgram = glCreateProgram();
    glAttachShader(shaderProgram, vertexShader);
    glAttachShader(shaderProgram, fragmentShader);
    glBindFragDataLocation(shaderProgram, 0, "outColor");
    glLinkProgram(shaderProgram);
    glUseProgram(shaderProgram);

    // Specify the layout of the vertex data
    GLint posAttrib = glGetAttribLocation(shaderProgram, "position");
    glEnableVertexAttribArray(posAttrib);
    glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), 0);

    GLint colAttrib = glGetAttribLocation(shaderProgram, "color");
    glEnableVertexAttribArray(colAttrib);
    glVertexAttribPointer(colAttrib, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (void *) (2 * sizeof(GLfloat)));

//    // Specify the layout of the vertex data
//    GLint posAttrib = glGetAttribLocation(shaderProgram, "position");
//    glEnableVertexAttribArray(posAttrib);
//    glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), 0);
//
//    GLint colAttrib = glGetAttribLocation(shaderProgram, "color");
//    glEnableVertexAttribArray(colAttrib);
//    glVertexAttribPointer(colAttrib, 1, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (void*)(2 * sizeof(GLfloat)));


//// GLEW

    while (!glfwWindowShouldClose(window)) {

        if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
            glfwSetWindowShouldClose(window, GL_TRUE);

        // Clear the screen to black
        glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);

        // Draw a rectangle from the 2 triangles using 6 indices
//        glDrawArrays(GL_TRIANGLES, 0, 3);
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);

        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    glDeleteProgram(shaderProgram);
    glDeleteShader(fragmentShader);
    glDeleteShader(vertexShader);

    glDeleteBuffers(1, &ebo);
    glDeleteBuffers(1, &vbo);

    glDeleteVertexArrays(1, &vao);

}
Exemplo n.º 7
0
/*!***************************************************************************
 @Function		Init
 @Input			pContext	A pointer to a PVRTContext
 @Input			bRotate		true to rotate texture 90 degrees.
 @Input			pszError	An option string for returning errors
 @Return 		PVR_SUCCESS on success
 @Description	Initialises the background
*****************************************************************************/
EPVRTError CPVRTBackground::Init(const SPVRTContext * const pContext, bool bRotate, CPVRTString *pszError)
{
	PVRT_UNREFERENCED_PARAMETER(pContext);

	Destroy();

	m_pAPI = new SPVRTBackgroundAPI;

	if(!m_pAPI)
	{
		if(pszError)
			*pszError = "Error: Insufficient memory to allocate SCPVRTBackgroundAPI.";

		return PVR_FAIL;
	}

	m_pAPI->m_ui32VertexShader = 0;
	m_pAPI->m_ui32FragShader = 0;
	m_pAPI->m_ui32ProgramObject = 0;
	m_pAPI->m_ui32VertexBufferObject = 0;

	bool bResult;
	CPVRTString sTmpErrStr;

	// The shader loading code doesn't expect a null pointer for the error string
	if(!pszError)
		pszError = &sTmpErrStr;

	/* Compiles the shaders. For a more detailed explanation, see IntroducingPVRTools */
#if defined(GL_SGX_BINARY_IMG)
	// Try binary shaders first
	bResult = (PVRTShaderLoadBinaryFromMemory(_BackgroundFragShader_fsc, _BackgroundFragShader_fsc_size,
					GL_FRAGMENT_SHADER, GL_SGX_BINARY_IMG, &m_pAPI->m_ui32FragShader, pszError) == PVR_SUCCESS)
		       && (PVRTShaderLoadBinaryFromMemory(_BackgroundVertShader_vsc, _BackgroundVertShader_vsc_size,
					GL_VERTEX_SHADER, GL_SGX_BINARY_IMG, &m_pAPI->m_ui32VertexShader, pszError) == PVR_SUCCESS);
	if(!bResult)
#endif
	{
		// if binary shaders don't work, try source shaders
		bResult = (PVRTShaderLoadSourceFromMemory(_BackgroundFragShader_fsh, GL_FRAGMENT_SHADER, &m_pAPI->m_ui32FragShader, pszError) == PVR_SUCCESS) &&
				(PVRTShaderLoadSourceFromMemory(_BackgroundVertShader_vsh, GL_VERTEX_SHADER, &m_pAPI->m_ui32VertexShader, pszError)  == PVR_SUCCESS);
	}

	_ASSERT(bResult);

	if(!bResult)
		return PVR_FAIL;

	// Reset the error string
	if(pszError)
		*pszError = "";

	// Create the shader program
	m_pAPI->m_ui32ProgramObject = glCreateProgram();

	// Attach the fragment and vertex shaders to it
	glAttachShader(m_pAPI->m_ui32ProgramObject, m_pAPI->m_ui32FragShader);
	glAttachShader(m_pAPI->m_ui32ProgramObject, m_pAPI->m_ui32VertexShader);

	// Bind the custom vertex attribute "myVertex" to location VERTEX_ARRAY
	glBindAttribLocation(m_pAPI->m_ui32ProgramObject, VERTEX_ARRAY, "myVertex");

	// Bind the custom vertex attribute "myUV" to location TEXCOORD_ARRAY
	glBindAttribLocation(m_pAPI->m_ui32ProgramObject, TEXCOORD_ARRAY, "myUV");

	// Link the program
	glLinkProgram(m_pAPI->m_ui32ProgramObject);
	GLint Linked;
	glGetProgramiv(m_pAPI->m_ui32ProgramObject, GL_LINK_STATUS, &Linked);
	if (!Linked)
	{
		int i32InfoLogLength, i32CharsWritten;
		glGetProgramiv(m_pAPI->m_ui32ProgramObject, GL_INFO_LOG_LENGTH, &i32InfoLogLength);
		char* pszInfoLog = new char[i32InfoLogLength];
		glGetProgramInfoLog(m_pAPI->m_ui32ProgramObject, i32InfoLogLength, &i32CharsWritten, pszInfoLog);
		*pszError = CPVRTString("Failed to link: ") + pszInfoLog + "\n";
		delete [] pszInfoLog;
		bResult = false;
	}

	_ASSERT(bResult);

	if(!bResult)
		return PVR_FAIL;

	// Use the loaded shader program
	glUseProgram(m_pAPI->m_ui32ProgramObject);

	// Set the sampler2D variable to the first texture unit
	glUniform1i(glGetUniformLocation(m_pAPI->m_ui32ProgramObject, "sampler2d"), 0);

	// Create the vertex buffer object
	GLfloat *pVertexData = 0;

	// The vertex data for non-rotated
	GLfloat afVertexData[16] = { -1, -1, 1, -1, -1, 1, 1, 1,
						0, 0, 1, 0, 0, 1, 1, 1};

	// The vertex data for rotated
	GLfloat afVertexDataRotated[16] = {-1, 1, -1, -1, 1, 1, 1, -1,
						1, 1, 0, 1, 1, 0, 0, 0};

	if(!bRotate)
		pVertexData = &afVertexData[0];
	else
		pVertexData = &afVertexDataRotated[0];

	glGenBuffers(1, &m_pAPI->m_ui32VertexBufferObject);
	glBindBuffer(GL_ARRAY_BUFFER, m_pAPI->m_ui32VertexBufferObject);

	glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 16, pVertexData, GL_STATIC_DRAW);

	glBindBuffer(GL_ARRAY_BUFFER, 0);

	m_bInit = true;

	return PVR_SUCCESS;
}
// Initialization code
void init()
{
	glewExperimental = GL_TRUE;
	// Initializes the glew library
	glewInit();

	// Read in the shader code from a file.
	std::string vertShader = readShader("VertexShader.glsl");
	std::string fragShader = readShader("FragmentShader.glsl");

	// createShader consolidates all of the shader compilation code
	vertex_shader = createShader(vertShader, GL_VERTEX_SHADER);
	fragment_shader = createShader(fragShader, GL_FRAGMENT_SHADER);

	// A shader is a program that runs on your GPU instead of your CPU. In this sense, OpenGL refers to your groups of shaders as "programs".
	// Using glCreateProgram creates a shader program and returns a GLuint reference to it.
	program = glCreateProgram();
	glAttachShader(program, vertex_shader);		// This attaches our vertex shader to our program.
	glAttachShader(program, fragment_shader);	// This attaches our fragment shader to our program.

	// This links the program, using the vertex and fragment shaders to create executables to run on the GPU.
	glLinkProgram(program);
	// End of shader and program creation

	// Do all the same for our compute shader and program
	std::string compShader = readShader("ComputeShader.glsl");
	compute_shader = createShader(compShader, GL_COMPUTE_SHADER);
	compute_program = glCreateProgram();
	glAttachShader(compute_program, compute_shader);
	glLinkProgram(compute_program);

	// Tell our code to use the compute program
	glUseProgram(compute_program);

	// Get the uniform location of the radius variable
	iLocRadius = glGetUniformLocation(compute_program, "radius");

	// Enables the depth test, which you will want in most cases. You can disable this in the render loop if you need to.
	glEnable(GL_DEPTH_TEST);

	// Create an std::vector and put our vertices into it. This is just going to be an empty array.
	std::vector<VertexFormat> vertices;//our vertex positions
	
	vertices.resize(256); // Resize the vector to 256, which creates 256 VertexFormat objects (using the default constructor) in an array.

	// Generate your vertex array object name.
	glGenVertexArrays(1, &vao);
	
	// Bind the vertex array object
	glBindVertexArray(vao);

	// This generates buffer object names
	// The first parameter is the number of buffer objects, and the second parameter is a pointer to an array of buffer objects (yes, before this call, vbo was an empty variable)
	// (In this example, there's only one buffer object.)
	glGenBuffers(1, &vbo);

	// Binds a named buffer object to the specified buffer binding point. Give it a target (GL_ARRAY_BUFFER) to determine where to bind the buffer.
	// There are several different target parameters, GL_ARRAY_BUFFER is for vertex attributes, feel free to Google the others to find out what else there is.
	// The second paramter is the buffer object reference. If no buffer object with the given name exists, it will create one.
	// Buffer object names are unsigned integers (like vbo). Zero is a reserved value, and there is no default buffer for each target (targets, like GL_ARRAY_BUFFER).
	// Passing in zero as the buffer name (second parameter) will result in unbinding any buffer bound to that target, and frees up the memory.
	glBindBuffer(GL_ARRAY_BUFFER, vbo);	

	// Creates and initializes a buffer object's data.
	// First parameter is the target, second parameter is the size of the buffer, third parameter is a pointer to the data that will copied into the buffer, and fourth parameter is the 
	// expected usage pattern of the data. Possible usage patterns: GL_STREAM_DRAW, GL_STREAM_READ, GL_STREAM_COPY, GL_STATIC_DRAW, GL_STATIC_READ, GL_STATIC_COPY, GL_DYNAMIC_DRAW, 
	// GL_DYNAMIC_READ, or GL_DYNAMIC_COPY
	// Stream means that the data will be modified once, and used only a few times at most. Static means that the data will be modified once, and used a lot. Dynamic means that the data 
	// will be modified repeatedly, and used a lot. Draw means that the data is modified by the application, and used as a source for GL drawing. Read means the data is modified by 
	// reading data from GL, and used to return that data when queried by the application. Copy means that the data is modified by reading from the GL, and used as a source for drawing.
	glBufferData(GL_ARRAY_BUFFER, sizeof(VertexFormat) * 256, &vertices[0], GL_STATIC_DRAW);
	// GL_ARRAY_BUFFER is for vertices in an array, all drawing commands of glDrawArrays will use vertices from that buffer.

	// By default, all client-side capabilities are disabled, including all generic vertex attribute arrays.
	// When enabled, the values in a generic vertex attribute array will be accessed and used for rendering when calls are made to vertex array commands (like glDrawArrays/glDrawElements)
	// A GL_INVALID_VALUE will be generated if the index parameter is greater than or equal to GL_MAX_VERTEX_ATTRIBS
	glEnableVertexAttribArray(0);

	// Defines an array of generic vertex attribute data. Takes an index, a size specifying the number of components (in this case, floats)(has a max of 4)
	// The third parameter, type, can be GL_BYTE, GL_UNSIGNED_BYTE, GL_SHORT, GL_UNSIGNED_SHORT, GL_FIXED, or GL_FLOAT
	// The fourth parameter specifies whether to normalize fixed-point data values, the fifth parameter is the stride which is the offset (in bytes) between generic vertex attributes
	// The fifth parameter is a pointer to the first component of the first generic vertex attribute in the array. If a named buffer object is bound to GL_ARRAY_BUFFER (and it is, in this case) 
	// then the pointer parameter is treated as a byte offset into the buffer object's data.
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(VertexFormat), (void*)16);
	// You'll note sizeof(VertexFormat) is our stride, because each vertex contains data that adds up to that size.
	// You'll also notice we offset this parameter by 16 bytes, this is because the vec3 position attribute is after the vec4 color attribute. A vec4 has 4 floats, each being 4 bytes 
	// so we offset by 4*4=16 to make sure that our first attribute is actually the position. The reason we put position after color in the struct has to do with padding.
	// For more info on padding, Google it.

	// This is our color attribute, so the offset is 0, and the size is 4 since there are 4 floats for color.
	glEnableVertexAttribArray(1);
	glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(VertexFormat), (void*)0);
	
	// Now we set our Shader Storage Buffer Object reference equal to our Vertex Buffer Object reference. This is crucial for our Compute Shader to be able to modify the values in 
	// that buffer.
	ssbo = vbo;

	// Binds a buffer object (ssbo) to a binding point at the given index (0 in this case) of the array of targets (GL_SHADER_STORAGE_BUFFER)
	glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, ssbo);

	// This gets us a reference to the uniform variable in the vertex shader, which is called "MVP".
	// We're using this variable as a 4x4 transformation matrix
	// Only 2 parameters required: A reference to the shader program and the name of the uniform variable within the shader code.
	uniMVP = glGetUniformLocation(program, "MVP");

	// Creates the view matrix using glm::lookAt.
	// First parameter is camera position, second parameter is point to be centered on-screen, and the third paramter is the up axis.
	view = glm::lookAt(	glm::vec3(0.0f, 0.0f, -1.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f));

	// Creates a projection matrix using glm::perspective.
	// First parameter is the vertical FoV (Field of View), second paramter is the aspect ratio, 3rd parameter is the near clipping plane, 4th parameter is the far clipping plane.
	proj = glm::perspective(45.0f, 800.0f / 600.0f, 0.1f, 100.0f);

	// This is not necessary, but I prefer to handle my vertices in the clockwise order. glFrontFace defines which face of the triangles you're drawing is the front.
	// Essentially, if you draw your vertices in counter-clockwise order, by default (in OpenGL) the front face will be facing you/the screen. If you draw them clockwise, the front face 
	// will face away from you. By passing in GL_CW to this function, we are saying the opposite, and now the front face will face you if you draw in the clockwise order.
	// If you don't use this, just reverse the order of the vertices in your array when you define them so that you draw the points in a counter-clockwise order.
	glFrontFace(GL_CW);
}
Exemplo n.º 9
0
bool TeapotRenderer::LoadShaders( SHADER_PARAMS* params,
        const char* strVsh,
        const char* strFsh )
{
    GLuint program;
    GLuint vert_shader, frag_shader;
    char *vert_shader_pathname, *frag_shader_pathname;

    // Create shader program
    program = glCreateProgram();
    LOGI( "Created Shader %d", program );

    // Create and compile vertex shader
    if( !ndk_helper::shader::CompileShader( &vert_shader, GL_VERTEX_SHADER, strVsh ) )
    {
        LOGI( "Failed to compile vertex shader" );
        glDeleteProgram( program );
        return false;
    }

    // Create and compile fragment shader
    if( !ndk_helper::shader::CompileShader( &frag_shader, GL_FRAGMENT_SHADER, strFsh ) )
    {
        LOGI( "Failed to compile fragment shader" );
        glDeleteProgram( program );
        return false;
    }

    // Attach vertex shader to program
    glAttachShader( program, vert_shader );

    // Attach fragment shader to program
    glAttachShader( program, frag_shader );

    // Bind attribute locations
    // this needs to be done prior to linking
    glBindAttribLocation( program, ATTRIB_VERTEX, "myVertex" );
    glBindAttribLocation( program, ATTRIB_NORMAL, "myNormal" );
    glBindAttribLocation( program, ATTRIB_UV, "myUV" );

    // Link program
    if( !ndk_helper::shader::LinkProgram( program ) )
    {
        LOGI( "Failed to link program: %d", program );

        if( vert_shader )
        {
            glDeleteShader( vert_shader );
            vert_shader = 0;
        }
        if( frag_shader )
        {
            glDeleteShader( frag_shader );
            frag_shader = 0;
        }
        if( program )
        {
            glDeleteProgram( program );
        }

        return false;
    }

    // Get uniform locations
    params->matrix_projection_ = glGetUniformLocation( program, "uPMatrix" );
    params->matrix_view_ = glGetUniformLocation( program, "uMVMatrix" );

    params->light0_ = glGetUniformLocation( program, "vLight0" );
    params->material_diffuse_ = glGetUniformLocation( program, "vMaterialDiffuse" );
    params->material_ambient_ = glGetUniformLocation( program, "vMaterialAmbient" );
    params->material_specular_ = glGetUniformLocation( program, "vMaterialSpecular" );

    // Release vertex and fragment shaders
    if( vert_shader )
        glDeleteShader( vert_shader );
    if( frag_shader )
        glDeleteShader( frag_shader );

    params->program_ = program;
    return true;
}
Exemplo n.º 10
0
// Create shaderprogram with a define container
bool gfx::ShaderProgram::LoadCompleteShaderProgramFromFile ( const rString& filename, bool print, ShaderDefineContainer& container )
{
    //this function is used to load a set of shaders from a single file
    //seperate each shader with a #new_shader ******* and a #end_shader
    //where **** can be a vertex, geometry, control, evaluation or fragment
    //extra code can be loaded into the current shader by the #include filename macro
    m_Filename = rString ( filename.c_str() );
    m_LoadedShaders = true;
	m_Defines = container;
    ifstream fin;
    fin.open ( filename.c_str() );
    if ( !fin.is_open() )
    {
        if ( print )
        {
			Logger::Log( "Could not open file " + filename, "ShaderProgram", LogSeverity::ERROR_MSG );
			return false;
        }
        return false;
    }
    rString line;
    size_t found;
    while ( !fin.eof() )
    {
        getline ( fin, line );
		if ( (found = line.find( "#new_shader" )) != rString::npos )
        {
			if ( (found = line.find( "vertex" )) != rString::npos )
            {
                CreateShader ( &fin, GL_VERTEX_SHADER, filename,print,container );
            }
			if ( (found = line.find( "geometry" )) != rString::npos )
            {
                CreateShader ( &fin, GL_GEOMETRY_SHADER, filename, print,container );
            }
			if ( (found = line.find( "control" )) != rString::npos )
            {
                CreateShader ( &fin, GL_TESS_CONTROL_SHADER, filename, print,container );
            }
			if ( (found = line.find( "evaluation" )) != rString::npos )
            {
                CreateShader ( &fin, GL_TESS_EVALUATION_SHADER, filename, print,container );
            }
			if ( (found = line.find( "fragment" )) != rString::npos )
            {
                CreateShader ( &fin, GL_FRAGMENT_SHADER, filename, print,container );
            }
			if ( (found = line.find( "compute" )) != rString::npos )
            {
                CreateShader ( &fin, GL_COMPUTE_SHADER, filename, print,container );
            }
        }
    }
    m_Handle = glCreateProgram();
    if ( m_Handle == 0 )
    {
        if ( print )
        {
			Logger::Log( "Could not create shader program", "ShaderProgram", LogSeverity::ERROR_MSG );
			return false;
        }
        return false;
    }
    //attach shaders to program
    for ( int i = 0; i < static_cast<int> ( m_Shaders.size() ); i++ )
    {
        glAttachShader ( m_Handle, m_Shaders[i]->GetHandle() );
    }
    //link shaders
    glLinkProgram ( m_Handle );
    //error checking
    GLint status;
    glGetProgramiv ( m_Handle, GL_LINK_STATUS, &status );
    if ( status == GL_FALSE )
    {
        char log[1024];
        int len = 0;
		Logger::Log( "Could not link shaders to program", "ShaderProgram", LogSeverity::ERROR_MSG );
        glGetProgramInfoLog ( m_Handle, sizeof ( log ), &len, log );
		Logger::Log( "Error log: " + rString( log ), "ShaderProgram", LogSeverity::ERROR_MSG );
		return false;
    }
    if ( print )
    {
		Logger::Log( "Linked Shaders to program", "ShaderProgram", LogSeverity::DEBUG_MSG );
    }
    Validate();
	return true;
}
Exemplo n.º 11
0
bool LoadShader(
    char* vertex_filename,
    char* geometry_filename,
    char* fragment_filename,
    GLuint* result)
{
    bool succeeded = true;

    *result = glCreateProgram();

    unsigned int vertex_shader;

    if (LoadShaderType(vertex_filename, GL_VERTEX_SHADER, &vertex_shader))
    {
        glAttachShader(*result, vertex_shader);
        glDeleteShader(vertex_shader);
    }
    else
    {
        printf("FAILED TO LOAD VERTEX SHADER\n");
    }

    if (geometry_filename != nullptr)
    {
        unsigned int geometry_shader;
        if (LoadShaderType(geometry_filename, GL_GEOMETRY_SHADER, &geometry_shader))
        {
            glAttachShader(*result, geometry_shader);
            glDeleteShader(geometry_shader);
        }
        else
        {
            printf("FAILED TO LOAD GEOMETRY SHADER\n");
        }
    }
    if (fragment_filename != nullptr)
    {
        unsigned int fragment_shader;
        if (LoadShaderType(fragment_filename, GL_FRAGMENT_SHADER, &fragment_shader))
        {
            glAttachShader(*result, fragment_shader);
            glDeleteShader(fragment_shader);
        }
        else
        {
            printf("FAILED TO LOAD FRAGMENT SHADER\n");
        }
    }

    glLinkProgram(*result);

    GLint success;
    glGetProgramiv(*result, GL_LINK_STATUS, &success);
    if (success == GL_FALSE)
    {
        GLint log_length;
        glGetProgramiv(*result, GL_INFO_LOG_LENGTH, &log_length);
        char* log = new char[log_length];
        glGetProgramInfoLog(*result, log_length, 0, log);

        printf("ERROR: STUFF DONE SCREWED UP IN UR SHADER BUDDY!\n\n");
        printf("%s", log);

        delete[] log;
        succeeded = false;
    }

    return succeeded;
}
Exemplo n.º 12
0
int main()
{
    // glfw: initialize and configure
    // ------------------------------
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

#ifdef __APPLE__
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // uncomment this statement to fix compilation on OS X
#endif

    // glfw window creation
    // --------------------
    GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", NULL, NULL);
    if (window == NULL)
    {
        std::cout << "Failed to create GLFW window" << std::endl;
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);
    glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);

    // glad: load all OpenGL function pointers
    // ---------------------------------------
    if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
    {
        std::cout << "Failed to initialize GLAD" << std::endl;
        return -1;
    }


    // build and compile our shader program
    // ------------------------------------
    // we skipped compile log checks this time for readability (if you do encounter issues, add the compile-checks! see previous code samples)
    unsigned int vertexShader = glCreateShader(GL_VERTEX_SHADER);
    unsigned int fragmentShaderOrange = glCreateShader(GL_FRAGMENT_SHADER); // the first fragment shader that outputs the color orange
    unsigned int fragmentShaderYellow = glCreateShader(GL_FRAGMENT_SHADER); // the second fragment shader that outputs the color yellow
    unsigned int shaderProgramOrange = glCreateProgram();
    unsigned int shaderProgramYellow = glCreateProgram(); // the second shader program
    glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
    glCompileShader(vertexShader);
    glShaderSource(fragmentShaderOrange, 1, &fragmentShader1Source, NULL);
    glCompileShader(fragmentShaderOrange);
    glShaderSource(fragmentShaderYellow, 1, &fragmentShader2Source, NULL);
    glCompileShader(fragmentShaderYellow);
    // link the first program object
    glAttachShader(shaderProgramOrange, vertexShader);
    glAttachShader(shaderProgramOrange, fragmentShaderOrange);
    glLinkProgram(shaderProgramOrange);
    // then link the second program object using a different fragment shader (but same vertex shader)
    // this is perfectly allowed since the inputs and outputs of both the vertex and fragment shaders are equally matched.
    glAttachShader(shaderProgramYellow, vertexShader);
    glAttachShader(shaderProgramYellow, fragmentShaderYellow);
    glLinkProgram(shaderProgramYellow);

    // set up vertex data (and buffer(s)) and configure vertex attributes
    // ------------------------------------------------------------------
    float firstTriangle[] = {
        -0.9f, -0.5f, 0.0f,  // left 
        -0.0f, -0.5f, 0.0f,  // right
        -0.45f, 0.5f, 0.0f,  // top 
    };
    float secondTriangle[] = {
        0.0f, -0.5f, 0.0f,  // left
        0.9f, -0.5f, 0.0f,  // right
        0.45f, 0.5f, 0.0f   // top 
    };
    unsigned int VBOs[2], VAOs[2];
    glGenVertexArrays(2, VAOs); // we can also generate multiple VAOs or buffers at the same time
    glGenBuffers(2, VBOs);
    // first triangle setup
    // --------------------
    glBindVertexArray(VAOs[0]);
    glBindBuffer(GL_ARRAY_BUFFER, VBOs[0]);
    glBufferData(GL_ARRAY_BUFFER, sizeof(firstTriangle), firstTriangle, GL_STATIC_DRAW);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);	// Vertex attributes stay the same
    glEnableVertexAttribArray(0);
    // glBindVertexArray(0); // no need to unbind at all as we directly bind a different VAO the next few lines
    // second triangle setup
    // ---------------------
    glBindVertexArray(VAOs[1]);	// note that we bind to a different VAO now
    glBindBuffer(GL_ARRAY_BUFFER, VBOs[1]);	// and a different VBO
    glBufferData(GL_ARRAY_BUFFER, sizeof(secondTriangle), secondTriangle, GL_STATIC_DRAW);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0); // because the vertex data is tightly packed we can also specify 0 as the vertex attribute's stride to let OpenGL figure it out
    glEnableVertexAttribArray(0);
    // glBindVertexArray(0); // not really necessary as well, but beware of calls that could affect VAOs while this one is bound (like binding element buffer objects, or enabling/disabling vertex attributes)


    // uncomment this call to draw in wireframe polygons.
    //glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);

    // render loop
    // -----------
    while (!glfwWindowShouldClose(window))
    {
        // input
        // -----
        processInput(window);

        // render
        // ------
        glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);

        // now when we draw the triangle we first use the vertex and orange fragment shader from the first program
        glUseProgram(shaderProgramOrange);
        // draw the first triangle using the data from our first VAO
        glBindVertexArray(VAOs[0]);
        glDrawArrays(GL_TRIANGLES, 0, 3);	// this call should output an orange triangle
        // then we draw the second triangle using the data from the second VAO
        // when we draw the second triangle we want to use a different shader program so we switch to the shader program with our yellow fragment shader.
        glUseProgram(shaderProgramYellow);
        glBindVertexArray(VAOs[1]);
        glDrawArrays(GL_TRIANGLES, 0, 3);	// this call should output a yellow triangle

        // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)
        // -------------------------------------------------------------------------------
        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    // optional: de-allocate all resources once they've outlived their purpose:
    // ------------------------------------------------------------------------
    glDeleteVertexArrays(2, VAOs);
    glDeleteBuffers(2, VBOs);

    // glfw: terminate, clearing all previously allocated GLFW resources.
    // ------------------------------------------------------------------
    glfwTerminate();
    return 0;
}
Exemplo n.º 13
0
static int gub_create_program()
{
    GLbyte vShaderStr[] =
        "attribute vec4 aPosition;    \n"
        "attribute vec2 aTexCoord;    \n"
        "varying vec2 vTexCoord;      \n"
        "void main()                  \n"
        "{                            \n"
        "   gl_Position = aPosition;  \n"
        "   vTexCoord = aTexCoord;    \n"
        "}                            \n";

    GLbyte fShaderStr[] =
        "precision mediump float;                          \n"
        "varying vec2 vTexCoord;                           \n"
        "uniform sampler2D sTexture;                       \n"
        "void main()                                       \n"
        "{                                                 \n"
        "  gl_FragColor = texture2D(sTexture, vTexCoord);  \n"
        "}                                                 \n";

    GLuint vertexShader;
    GLuint fragmentShader;
    GLuint programObject;
    GLint linked;

    // Load the vertex/fragment shaders
    vertexShader = gub_load_shader(GL_VERTEX_SHADER, vShaderStr);
    fragmentShader = gub_load_shader(GL_FRAGMENT_SHADER, fShaderStr);

    // Create the program object
    programObject = glCreateProgram();

    if (programObject == 0)
        return 0;

    glAttachShader(programObject, vertexShader);
    glAttachShader(programObject, fragmentShader);

    // Bind aPosition to attribute 0 and aTexCoord to attribute 1
    glBindAttribLocation(programObject, 0, "aPosition");
    glBindAttribLocation(programObject, 1, "aTexCoord");

    // Link the program
    glLinkProgram(programObject);

    // Check the link status
    glGetProgramiv(programObject, GL_LINK_STATUS, &linked);

    if (!linked) {
        GLint infoLen = 0;
        glGetProgramiv(programObject, GL_INFO_LOG_LENGTH, &infoLen);
        if (infoLen > 1) {
            char* infoLog = malloc(sizeof(char) * infoLen);
            glGetProgramInfoLog(programObject, infoLen, NULL, infoLog);
            gub_log("Error linking program: %s", infoLog);
            free(infoLog);
        }
        glDeleteProgram(programObject);
        return 0;
    }

    // Store the program object
    return programObject;
}
Exemplo n.º 14
0
enum piglit_result
piglit_display(void)
{
	const char *vs_ssbo_template =
		"#version 130\n"
		"#extension GL_ARB_shader_storage_buffer_object : enable\n"
		"#extension GL_ARB_uniform_buffer_object : enable\n"
		"\n"
		"varying vec4 vary;"
		"in vec4 piglit_vertex;\n"
		"\n"
		"layout(std140) buffer ssbo {\n"
		"	vec4 v[%d];\n"
		"};\n"
		"uniform int i;\n"
		"\n"
		"void main() {\n"
		"	gl_Position = piglit_vertex;\n"
		"	vary = v[i];\n"
		"}\n";

	const char *fs_template =
		"#version 130\n"
		"#extension GL_ARB_shader_storage_buffer_object : enable\n"
		"\n"
		"varying vec4 vary;"
		"\n"
		"void main() {\n"
		"	gl_FragColor = vary;\n"
		"}\n";

	const char *vs_template =
		"#version 130\n"
		"#extension GL_ARB_shader_storage_buffer_object : enable\n"
		"in vec4 piglit_vertex;\n"
		"\n"
		"void main() {\n"
		"	gl_Position = piglit_vertex;\n"
		"}\n";

	const char *fs_ssbo_template =
		"#version 130\n"
		"#extension GL_ARB_shader_storage_buffer_object : enable\n"
		"#extension GL_ARB_uniform_buffer_object : enable\n"
		"\n"
		"layout(std140) buffer ssbo {\n"
		"	vec4 v[%d];\n"
		"};\n"
		"uniform int i;\n"
		"\n"
		"void main() {\n"
		"	gl_FragColor = v[i];\n"
		"}\n";

	char *vs_source, *fs_source;
	GLint max_size, vec4s, i_location;
	GLuint vs, fs, prog, bo;
	GLenum target;
	float *data;
	size_t size;
	bool pass = true;
	bool link_should_fail;
	const float green[4] = { 0, 1, 0, 0 };
	int test_index;

	piglit_require_extension("GL_ARB_shader_storage_buffer_object");
	piglit_require_extension("GL_ARB_uniform_buffer_object");

	glGetIntegerv(GL_MAX_SHADER_STORAGE_BLOCK_SIZE, &max_size);
	printf("Max shader storage block size: %d\n", max_size);
	vec4s = max_size / 4 / 4;

	switch (mode) {
	case VS:
		target = GL_VERTEX_SHADER;
		link_should_fail = false;
		test_index = vec4s - 1;
		break;
	case VS_EXCEED:
		target = GL_VERTEX_SHADER;
		link_should_fail = true;
		vec4s++;
		test_index = vec4s - 2;
		break;
	case FS:
		target = GL_FRAGMENT_SHADER;
		link_should_fail = false;
		test_index = vec4s - 1;
		break;
	case FS_EXCEED:
		target = GL_FRAGMENT_SHADER;
		link_should_fail = true;
		vec4s++;
		test_index = vec4s - 2;
		break;
	default:
		assert(false);
		target = GL_NONE;
		link_should_fail = false;
	}

	switch (target) {
	case GL_VERTEX_SHADER:
		(void)!asprintf(&vs_source, vs_ssbo_template, vec4s);
		(void)!asprintf(&fs_source, "%s", fs_template);
		printf("Testing VS with shader storage block vec4 v[%d]\n", vec4s);
		break;
	case GL_FRAGMENT_SHADER:
		(void)!asprintf(&vs_source, "%s", vs_template);
		(void)!asprintf(&fs_source, fs_ssbo_template, vec4s);
		printf("Testing FS with shader storage block vec4 v[%d]\n", vec4s);
		break;
	default:
		piglit_report_result(PIGLIT_FAIL);
	}

	vs = piglit_compile_shader_text(GL_VERTEX_SHADER, vs_source);
	fs = piglit_compile_shader_text(GL_FRAGMENT_SHADER, fs_source);

	prog = glCreateProgram();
	glAttachShader(prog, vs);
	glAttachShader(prog, fs);
	glLinkProgram(prog);

	if (link_should_fail) {
		if (!piglit_link_check_status_quiet(prog)) {
			printf("Failed to link with shader storage block vec4 "
			       "v[%d]\n", vec4s);
			piglit_report_result(PIGLIT_PASS);
		}
	} else {
		if (!piglit_link_check_status_quiet(prog)) {
			fprintf(stderr,
				"Failed to link with shader storage block vec4 "
				"v[%d]\n", vec4s);
			return PIGLIT_FAIL;
		}
	}

	size = vec4s * 4 * sizeof(float);
	glGenBuffers(1, &bo);
	glBindBuffer(GL_SHADER_STORAGE_BUFFER, bo);
	glBufferData(GL_SHADER_STORAGE_BUFFER, size, NULL, GL_DYNAMIC_DRAW);
	data = glMapBuffer(GL_SHADER_STORAGE_BUFFER, GL_READ_WRITE);
	memset(data, 0, size);

	/* The whole shader storage buffer will be zeros, except for the
	 * entry at v[test_index] which will be green.
	 */
	data[test_index * 4 + 0] = green[0];
	data[test_index * 4 + 1] = green[1];
	data[test_index * 4 + 2] = green[2];
	data[test_index * 4 + 3] = green[3];
	glUnmapBuffer(GL_SHADER_STORAGE_BUFFER);

	glUseProgram(prog);
	i_location = glGetUniformLocation(prog, "i");
	glUniform1i(i_location, test_index);

	glShaderStorageBlockBinding(prog, 0, 0);
	glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, bo);
	piglit_draw_rect(-1, -1, 2, 2);

	pass = piglit_probe_rect_rgba(0, 0, piglit_width, piglit_height, green);

	glDeleteProgram(prog);

	piglit_present_results();

	return pass ? PIGLIT_PASS : PIGLIT_FAIL;
}
Exemplo n.º 15
0
// Create, compile and link program.
void ShaderProgram::createCompileLink()
{
	m_programName = glCreateProgram();
	for (std::map<GLenum, Shader *>::iterator it = m_shaders.begin(); it != m_shaders.end(); ++it)
	{
		(it->second)->createShader();
		glAttachShader(m_programName,(it->second)->shaderName());
	}

	checkOpenGLError("Error attaching shaders.");

	bool shaderCompilationFailed = false;
	for (std::map<GLenum, Shader *>::iterator it = m_shaders.begin(); it != m_shaders.end(); ++it)
	{
		GLint compileStatus = (it->second)->compile();
		if (compileStatus == GL_FALSE){
			shaderCompilationFailed = true;
			displayShaderCompileLog("Shader compilation failed", *(it->second));
		}
	}

	checkOpenGLError("Error compiling shaders.");
	
	// fail if some compilation failed
	if (shaderCompilationFailed)
		std::cout << "ERROR: Shader compilation failed" << std::endl;

	// "bind" vertex attribute channels
	for (auto& attrib : m_attribs){
		glBindAttribLocation(m_programName, attrib.second.index, attrib.second.name.c_str());
	}

	checkOpenGLError("Error binding attrib locations.");

	// link program and check for errors
	GLint linkResult = linkProgram();
	if (linkResult == GL_FALSE) {
		displayProgramLinkingLog("Shader Program linking failed");
	}

	// get uniform ids
	for (std::map<std::string, UniformData>::iterator it = m_uniforms.begin(); it != m_uniforms.end(); ++it) {
		const std::string &uniName = it->second.name;
		GLint loc = glGetUniformLocation(m_programName, uniName.c_str());
		it->second.id = loc;

		if (loc == -1) {
			std::cerr << "[Warning] Uniform not found: '" << uniName << "'" << std::endl;
		}
	}

	checkOpenGLError("Error getting unfiorm locations.");

	// bind uniform blocks (the buffer still needs to be assigned to the same bind point)
	for (std::map<std::string, UniformBlockData>::iterator it = m_uniformBlocks.begin(); it != m_uniformBlocks.end(); ++it) {
		const std::string &blockName = it->second.name;
		GLuint blockIndex = glGetUniformBlockIndex(m_programName, blockName.c_str());
		glUniformBlockBinding(m_programName, blockIndex, it->second.bindPoint);
	}

	checkOpenGLError("Error binding uniform blocks.");
}
Exemplo n.º 16
0
// Set up the shaders, compile and link them, get pointers to 
// where the shader variables are in GPU memory. 
int init_resources()
{
  // Error flag is initially false
  GLint link_ok = GL_FALSE;
  // Indices for vertex and fragment shaders
  GLuint vs, fs;

  // create_shader is a function in shader_utils that reads in 
  // a vertex or fragment program from a file, creates a shader 
  // object, puts the program into the object, and compiles it.
  // If all goes well, returns 1. 
  vs = create_shader("plant.v.glsl", GL_VERTEX_SHADER);
  if (vs == 0) return 0;

  fs = create_shader("plant.f.glsl", GL_FRAGMENT_SHADER);
  if (fs == 0) return 0;


  // The GPU program contains both the vertex and shader programs. 
  program = glCreateProgram();
  glAttachShader(program, vs);
  glAttachShader(program, fs);

  // Link them together.
  glLinkProgram(program);
  glGetProgramiv(program, GL_LINK_STATUS, &link_ok);
  if (!link_ok) {
    fprintf(stderr, "glLinkProgram: failed\n");
    return 0;
  }
  
  // Now figure out where the linker put everything
  // We don't know where the vertex program is going to store all its
  // input data until after linking. 
  // Results are indicies into some table on the GPU. 

  // Ask for the index of shader variable coord2d. 
  attribute_coord2d = glGetAttribLocation(program, "coord2d");
  if (attribute_coord2d == -1) {
    fprintf(stderr, "Could not bind attribute coord2d\n");
    return 0;
  }

  // Ask for the index of shader variable coord2d. 
  attribute_color = glGetAttribLocation(program, "v_color");
  if (attribute_color == -1) {
    fprintf(stderr, "Could not bind attribute v_color\n");
    return 0;
  }

  // Get linker's index to the uniform variable
  uniform_matrix = glGetUniformLocation(program, "m_transform");
  if (uniform_matrix == -1) {
    fprintf(stderr, "Could not bind uniform variable m_transform \n");
    return 0;
  }


  // If all went well....
  return 1;
}
Exemplo n.º 17
0
 void Program::attach(const Shader* shader)
 {
     glAttachShader(id_, shader->getId());
 }
Exemplo n.º 18
0
	void initGLStuff()
	{
		// upload the quad vertices to the buffer
		glGenBuffers(1,&quadVertexBuffer);
		GLfloat quadVertices[] = {
			0,0,0,
			0,1,0,
			1,0,0,
			1,1,0,
			1,0,0,
			0,1,0,
		};
		glBindBuffer(GL_ARRAY_BUFFER, quadVertexBuffer);
		glBufferData(GL_ARRAY_BUFFER,
			sizeof(GLfloat)*6*3, quadVertices, GL_STATIC_DRAW);
		
		// same for uvs
		glGenBuffers(1,&quadUVBuffer);
		setQuadUVs(0,0,1,1);
		
		//// SHADERS ////
		
		// Create the shaders
		GLuint VertexShaderID = glCreateShader(GL_VERTEX_SHADER);
		GLuint FragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER);

		// Hard-coded shaders
		// Any other way toinclude them at compile time,
		// without depending on external files ?
		std::string VertexShaderCode =
			"#version 120" "\n"
			"attribute vec3 vertexPosition;" "\n"
			"attribute vec2 vertexUV;" "\n"
			"varying vec2 uv;" "\n"
			"uniform mat4 MVP;" "\n"
			"void main()" "\n"
			"{" "\n"
			"	vec4 v = vec4(vertexPosition, 1.0);" "\n"
			"	gl_Position = MVP*v;" "\n"
			"	uv = vertexUV;" "\n"
			"}" "\n";
			
		std::string FragmentShaderCode = 
			"#version 120" "\n"
			"varying vec2 uv;" "\n"
			"uniform vec4 color;" "\n"
			"uniform sampler2D textureSampler;" "\n"
			"void main()" "\n"
			"{" "\n"
			"	gl_FragColor = texture2D(textureSampler,uv)*color;" "\n"
			"}" "\n";
		GLint Result = GL_FALSE;
		int InfoLogLength;

		// Compile Vertex Shader
		char const * VertexSourcePointer = VertexShaderCode.c_str();
		glShaderSource(VertexShaderID, 1, &VertexSourcePointer , NULL);
		glCompileShader(VertexShaderID);

		// Check Vertex Shader
		// TODO Check shaders and programs if some debug bool is true
		/*glGetShaderiv(VertexShaderID, GL_COMPILE_STATUS, &Result);
		glGetShaderiv(VertexShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength);
		if ( InfoLogLength > 0 ){
			std::vector<char> VertexShaderErrorMessage(InfoLogLength+1);
			glGetShaderInfoLog(VertexShaderID, InfoLogLength, NULL, &VertexShaderErrorMessage[0]);
			std::cerr << &VertexShaderErrorMessage[0] << std::endl;
		}*/

		// Compile Fragment Shader
		char const * FragmentSourcePointer = FragmentShaderCode.c_str();
		glShaderSource(FragmentShaderID, 1, &FragmentSourcePointer , NULL);
		glCompileShader(FragmentShaderID);

		// Check Fragment Shader
		/*glGetShaderiv(FragmentShaderID, GL_COMPILE_STATUS, &Result);
		glGetShaderiv(FragmentShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength);
		if ( InfoLogLength > 0 ){
			std::vector<char> FragmentShaderErrorMessage(InfoLogLength+1);
			glGetShaderInfoLog(FragmentShaderID, InfoLogLength, NULL, &FragmentShaderErrorMessage[0]);
			std::cerr << &FragmentShaderErrorMessage[0] << std::endl;
		}*/

		// Link the program
		GLuint ProgramID = glCreateProgram();
		glAttachShader(ProgramID, VertexShaderID);
		glAttachShader(ProgramID, FragmentShaderID);
		glLinkProgram(ProgramID);

		// Check the program
		/*glGetProgramiv(ProgramID, GL_LINK_STATUS, &Result);
		glGetProgramiv(ProgramID, GL_INFO_LOG_LENGTH, &InfoLogLength);
		if ( InfoLogLength > 0 ){
			std::vector<char> ProgramErrorMessage(InfoLogLength+1);
			glGetProgramInfoLog(ProgramID, InfoLogLength, NULL, &ProgramErrorMessage[0]);
			std::cerr << &ProgramErrorMessage[0] << std::endl;
		}*/

		glDeleteShader(VertexShaderID);
		glDeleteShader(FragmentShaderID);

		program = ProgramID;
	}
Exemplo n.º 19
0
static void init_shaders(CUBE_STATE_T *state)
{
   static const GLfloat vertex_data[] = {
        -1.0,-1.0,1.0,1.0,
        1.0,-1.0,1.0,1.0,
        1.0,1.0,1.0,1.0,
        -1.0,1.0,1.0,1.0
   };
   const GLchar *vshader_source =
       "attribute vec4 vertex;"
       "void main(void) {"
       " vec4 pos = vertex;"
       " gl_Position = pos;"
       "}";

   const GLchar *fshader_source =
       "void main(void) {"
       "  gl_FragColor = vec4(0,1,0,1);"
       "}";

   state->vshader = glCreateShader(GL_VERTEX_SHADER);
   glShaderSource(state->vshader, 1, &vshader_source, 0);
   glCompileShader(state->vshader);
   check();

   if (state->verbose)
       showlog(state->vshader);

   state->fshader = glCreateShader(GL_FRAGMENT_SHADER);
   glShaderSource(state->fshader, 1, &fshader_source, 0);
   glCompileShader(state->fshader);
   check();

   if (state->verbose)
       showlog(state->fshader);

   state->program = glCreateProgram();
   glAttachShader(state->program, state->vshader);
   glAttachShader(state->program, state->fshader);
   glLinkProgram(state->program);
   check();

   if (state->verbose)
       showprogramlog(state->program);

   state->attr_vertex = glGetAttribLocation(state->program, "vertex");
#if 0
   state->unif_color  = glGetUniformLocation(state->program, "color");
   state->unif_scale  = glGetUniformLocation(state->program, "scale");
   state->unif_offset = glGetUniformLocation(state->program, "offset");
   state->unif_tex    = glGetUniformLocation(state->program, "tex");       
   state->unif_centre = glGetUniformLocation(state->program, "centre");
#endif
   check();

   glClearColor ( 0.0, 1.0, 1.0, 1.0 );

   glGenBuffers(1, &state->buf);

   check();

   // Prepare a texture image
   glGenTextures(1, &state->tex);
   check();
   glBindTexture(GL_TEXTURE_2D,state->tex);
   check();
   // glActiveTexture(0)
   glTexImage2D(GL_TEXTURE_2D,0,GL_RGB,state->screen_width,state->screen_height,0,GL_RGB,GL_UNSIGNED_SHORT_5_6_5,0);
   check();
   glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
   glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
   check();
   // Prepare a framebuffer for rendering
   glGenFramebuffers(1,&state->tex_fb);
   check();
   glBindFramebuffer(GL_FRAMEBUFFER,state->tex_fb);
   check();
   glFramebufferTexture2D(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT0,GL_TEXTURE_2D,state->tex,0);
   check();
   glBindFramebuffer(GL_FRAMEBUFFER,0);
   check();
   // Prepare viewport
   glViewport ( 0, 0, state->screen_width, state->screen_height );
   check();

   // Upload vertex data to a buffer
   glBindBuffer(GL_ARRAY_BUFFER, state->buf);
   glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_data),
           vertex_data, GL_STATIC_DRAW);
   glVertexAttribPointer(state->attr_vertex, 4, GL_FLOAT, 0, 16, 0);
   glEnableVertexAttribArray(state->attr_vertex);
   check();
}
Exemplo n.º 20
0
bool Shader::LoadFromFile(const char *pathVertex, const char *pathFragment)
{
	m_VertexShaderObj = glCreateShader(GL_VERTEX_SHADER);
	m_FragmentShaderObj = glCreateShader(GL_FRAGMENT_SHADER);
	m_Program = glCreateProgram();
	std::ifstream fileVer;
	std::ifstream fileFrag;
	fileVer.open(pathVertex);

	if (fileVer.is_open())
	{
		std::string buffer;

		while (fileVer.good())
		{
			std::getline(fileVer, buffer);
			m_VertexSource.append(buffer + "\n");

		}

		fileVer.close();
	}
	else
	{
		std::cout << "Cannot open shader file: " << pathVertex << std::endl;
		return false;
	}

	fileFrag.open(pathFragment);

	if (fileFrag.is_open())
	{
		std::string buffer;

		while (fileFrag.good())
		{
			getline(fileFrag, buffer);
			m_FragmentSource.append(buffer + "\n");
		}

		fileFrag.close();
	}
	else
	{
		std::cout << "Cannot open shader file: " << pathFragment << std::endl;
		return false;
	}

	const char *vP = m_VertexSource.c_str();
	const char *vF = m_FragmentSource.c_str();

	glShaderSource(m_VertexShaderObj, 1, &vP, NULL);
	glCompileShader(m_VertexShaderObj);
	GLint Result;
	GLint InfoLogLength;
	glGetShaderiv(m_VertexShaderObj, GL_COMPILE_STATUS, &Result);
	glGetShaderiv(m_VertexShaderObj, GL_INFO_LOG_LENGTH, &InfoLogLength);
	std::vector<char> VertexShaderErrorMessage(InfoLogLength);
	glGetShaderInfoLog(m_VertexShaderObj, InfoLogLength, NULL, &VertexShaderErrorMessage[0]);
	printf("Shader (Vertex): %s\n", &VertexShaderErrorMessage[0]);

	glShaderSource(m_FragmentShaderObj, 1, &vF, NULL);
	glCompileShader(m_FragmentShaderObj);
	glGetShaderiv(m_FragmentShaderObj, GL_COMPILE_STATUS, &Result);
	glGetShaderiv(m_FragmentShaderObj, GL_INFO_LOG_LENGTH, &InfoLogLength);
	VertexShaderErrorMessage = std::vector<char>(InfoLogLength);
	glGetShaderInfoLog(m_FragmentShaderObj, InfoLogLength, NULL, &VertexShaderErrorMessage[0]);
	printf("Shader (Fragment): %s\n", &VertexShaderErrorMessage[0]);
	
	glAttachShader(m_Program, m_VertexShaderObj);
	glAttachShader(m_Program, m_FragmentShaderObj);
	glLinkProgram(m_Program);
	glDeleteShader(m_VertexShaderObj);
	glDeleteShader(m_FragmentShaderObj);
	return true;
}
Exemplo n.º 21
0
static glw_program_t *
glw_link_program(glw_backend_root_t *gbr, const char *title,
		 GLuint vs, GLuint fs)
{
  char log[4096];
  GLsizei len;
  GLint v;
  GLuint p;
  int i;

  p = glCreateProgram();
  glAttachShader(p, vs);
  glAttachShader(p, fs);

  glBindAttribLocation(p, 0, "a_position");
  glBindAttribLocation(p, 1, "a_color");
  glBindAttribLocation(p, 2, "a_texcoord");


  glLinkProgram(p);

  glGetProgramInfoLog(p, sizeof(log), &len, log); 

  glGetProgramiv(p, GL_LINK_STATUS, &v);
  if(!v) {
    TRACE(TRACE_ERROR, "GLW", "Unable to link shader %s", title);
    TRACE(TRACE_ERROR, "GLW", "%s", log);
    return NULL;
  }

  glw_program_t *gp = calloc(1, sizeof(glw_program_t));

  gp->gp_title = strdup(title);
  gp->gp_program = p;

  glUseProgram(p);
  gbr->gbr_current = gp;


  gp->gp_attribute_position = 0;
  gp->gp_attribute_color    = 1;
  gp->gp_attribute_texcoord = 2;

  gp->gp_uniform_modelview  = glGetUniformLocation(p, "u_modelview");
  gp->gp_uniform_color      = glGetUniformLocation(p, "u_color");
  gp->gp_uniform_colormtx   = glGetUniformLocation(p, "u_colormtx");
  gp->gp_uniform_blend      = glGetUniformLocation(p, "u_blend");
  gp->gp_uniform_color_offset= glGetUniformLocation(p, "u_color_offset");
  gp->gp_uniform_blur        = glGetUniformLocation(p, "u_blur");
  gp->gp_uniform_time        = glGetUniformLocation(p, "time");
  gp->gp_uniform_resolution  = glGetUniformLocation(p, "resolution");

#ifdef DEBUG_SHADERS
  printf("Loaded %s\n", title);
  printf("  a_position     = %d\n", gp->gp_attribute_position);
  printf("  a_texcoord     = %d\n", gp->gp_attribute_texcoord);
  printf("  a_color        = %d\n", gp->gp_attribute_color);

  printf("  u_modelview = %d\n", gp->gp_uniform_modelview);
  printf("  u_color     = %d\n", gp->gp_uniform_color);
  printf("  u_colormtx  = %d\n", gp->gp_uniform_colormtx);
  printf("  u_blend     = %d\n", gp->gp_uniform_blend);
  printf("  u_color_offset = %d\n", gp->gp_uniform_color_offset);
  printf("  u_blur         = %d\n", gp->gp_uniform_blur);
#endif

  for(i = 0; i < 6; i++) {
    char name[8];
    snprintf(name, sizeof(name), "u_t%d", i);
    gp->gp_uniform_t[i]         = glGetUniformLocation(p, name);
    if(gp->gp_uniform_t[i] != -1)
      glUniform1i(gp->gp_uniform_t[i], i);
#ifdef DEBUG_SHADERS
    printf("  u_t%d       = %d\n", i, gp->gp_uniform_t[i]);
#endif
  }

  return gp;
}
Exemplo n.º 22
0
void processFn(struct fnargs* args) {
	switch (args->fn) {
	case glfnUNDEFINED:
		abort(); // bad glfn
		break;
	case glfnActiveTexture:
		glActiveTexture((GLenum)args->a0);
		break;
	case glfnAttachShader:
		glAttachShader((GLint)args->a0, (GLint)args->a1);
		break;
	case glfnBindAttribLocation:
		glBindAttribLocation((GLint)args->a0, (GLint)args->a1, (GLchar*)args->a2);
		free((void*)args->a2);
		break;
	case glfnBindBuffer:
		glBindBuffer((GLenum)args->a0, (GLuint)args->a1);
		break;
	case glfnBindFramebuffer:
		glBindFramebuffer((GLenum)args->a0, (GLint)args->a1);
		break;
	case glfnBindRenderbuffer:
		glBindRenderbuffer((GLenum)args->a0, (GLint)args->a1);
		break;
	case glfnBindTexture:
		glBindTexture((GLenum)args->a0, (GLint)args->a1);
		break;
	case glfnBlendColor:
		glBlendColor(*(GLfloat*)&args->a0, *(GLfloat*)&args->a1, *(GLfloat*)&args->a2, *(GLfloat*)&args->a3);
		break;
	case glfnBlendEquation:
		glBlendEquation((GLenum)args->a0);
		break;
	case glfnBlendEquationSeparate:
		glBlendEquationSeparate((GLenum)args->a0, (GLenum)args->a1);
		break;
	case glfnBlendFunc:
		glBlendFunc((GLenum)args->a0, (GLenum)args->a1);
		break;
	case glfnBlendFuncSeparate:
		glBlendFuncSeparate((GLenum)args->a0, (GLenum)args->a1, (GLenum)args->a2, (GLenum)args->a3);
		break;
	case glfnBufferData:
		glBufferData((GLenum)args->a0, (GLsizeiptr)args->a1, (GLvoid*)args->a2, (GLenum)args->a3);
		break;
	case glfnBufferSubData:
		glBufferSubData((GLenum)args->a0, (GLint)args->a1, (GLsizeiptr)args->a2, (GLvoid*)args->a3);
		break;
	case glfnCheckFramebufferStatus:
		ret = glCheckFramebufferStatus((GLenum)args->a0);
		break;
	case glfnClear:
		glClear((GLenum)args->a0);
		break;
	case glfnClearColor:
		glClearColor(*(GLfloat*)&args->a0, *(GLfloat*)&args->a1, *(GLfloat*)&args->a2, *(GLfloat*)&args->a3);
		break;
	case glfnClearDepthf:
		glClearDepthf(*(GLfloat*)&args->a0);
		break;
	case glfnClearStencil:
		glClearStencil((GLint)args->a0);
		break;
	case glfnColorMask:
		glColorMask((GLboolean)args->a0, (GLboolean)args->a1, (GLboolean)args->a2, (GLboolean)args->a3);
		break;
	case glfnCompileShader:
		glCompileShader((GLint)args->a0);
		break;
	case glfnCompressedTexImage2D:
		glCompressedTexImage2D((GLenum)args->a0, (GLint)args->a1, (GLenum)args->a2, (GLint)args->a3, (GLint)args->a4, (GLint)args->a5, (GLsizeiptr)args->a6, (GLvoid*)args->a7);
		break;
	case glfnCompressedTexSubImage2D:
		glCompressedTexSubImage2D((GLenum)args->a0, (GLint)args->a1, (GLint)args->a2, (GLint)args->a3, (GLint)args->a4, (GLint)args->a5, (GLenum)args->a6, (GLsizeiptr)args->a7, (GLvoid*)args->a8);
		break;
	case glfnCopyTexImage2D:
		glCopyTexImage2D((GLenum)args->a0, (GLint)args->a1, (GLenum)args->a2, (GLint)args->a3, (GLint)args->a4, (GLint)args->a5, (GLint)args->a6, (GLint)args->a7);
		break;
	case glfnCopyTexSubImage2D:
		glCopyTexSubImage2D((GLenum)args->a0, (GLint)args->a1, (GLint)args->a2, (GLint)args->a3, (GLint)args->a4, (GLint)args->a5, (GLint)args->a6, (GLint)args->a7);
		break;
	case glfnCreateProgram:
		ret = glCreateProgram();
		break;
	case glfnCreateShader:
		ret = glCreateShader((GLenum)args->a0);
		break;
	case glfnCullFace:
		glCullFace((GLenum)args->a0);
		break;
	case glfnDeleteBuffer:
		glDeleteBuffers(1, (const GLuint*)(&args->a0));
		break;
	case glfnDeleteFramebuffer:
		glDeleteFramebuffers(1, (const GLuint*)(&args->a0));
		break;
	case glfnDeleteProgram:
		glDeleteProgram((GLint)args->a0);
		break;
	case glfnDeleteRenderbuffer:
		glDeleteRenderbuffers(1, (const GLuint*)(&args->a0));
		break;
	case glfnDeleteShader:
		glDeleteShader((GLint)args->a0);
		break;
	case glfnDeleteTexture:
		glDeleteTextures(1, (const GLuint*)(&args->a0));
		break;
	case glfnDepthFunc:
		glDepthFunc((GLenum)args->a0);
		break;
	case glfnDepthMask:
		glDepthMask((GLboolean)args->a0);
		break;
	case glfnDepthRangef:
		glDepthRangef(*(GLfloat*)&args->a0, *(GLfloat*)&args->a1);
		break;
	case glfnDetachShader:
		glDetachShader((GLint)args->a0, (GLint)args->a1);
		break;
	case glfnDisable:
		glDisable((GLenum)args->a0);
		break;
	case glfnDisableVertexAttribArray:
		glDisableVertexAttribArray((GLint)args->a0);
		break;
	case glfnDrawArrays:
		glDrawArrays((GLenum)args->a0, (GLint)args->a1, (GLint)args->a2);
		break;
	case glfnDrawElements:
		glDrawElements((GLenum)args->a0, (GLint)args->a1, (GLenum)args->a2, (void*)args->a3);
		break;
	case glfnEnable:
		glEnable((GLenum)args->a0);
		break;
	case glfnEnableVertexAttribArray:
		glEnableVertexAttribArray((GLint)args->a0);
		break;
	case glfnFinish:
		glFinish();
		break;
	case glfnFlush:
		glFlush();
		break;
	case glfnFramebufferRenderbuffer:
		glFramebufferRenderbuffer((GLenum)args->a0, (GLenum)args->a1, (GLenum)args->a2, (GLint)args->a3);
		break;
	case glfnFramebufferTexture2D:
		glFramebufferTexture2D((GLenum)args->a0, (GLenum)args->a1, (GLenum)args->a2, (GLint)args->a3, (GLint)args->a4);
		break;
	case glfnFrontFace:
		glFrontFace((GLenum)args->a0);
		break;
	case glfnGenBuffer:
		glGenBuffers(1, (GLuint*)&ret);
		break;
	case glfnGenFramebuffer:
		glGenFramebuffers(1, (GLuint*)&ret);
		break;
	case glfnGenRenderbuffer:
		glGenRenderbuffers(1, (GLuint*)&ret);
		break;
	case glfnGenTexture:
		glGenTextures(1, (GLuint*)&ret);
		break;
	case glfnGenerateMipmap:
		glGenerateMipmap((GLenum)args->a0);
		break;
	case glfnGetActiveAttrib:
		glGetActiveAttrib(
			(GLuint)args->a0,
			(GLuint)args->a1,
			(GLsizei)args->a2,
			NULL,
			(GLint*)args->a4,
			(GLenum*)args->a5,
			(GLchar*)args->a6);
		break;
	case glfnGetActiveUniform:
		glGetActiveUniform(
			(GLuint)args->a0,
			(GLuint)args->a1,
			(GLsizei)args->a2,
			NULL,
			(GLint*)args->a4,
			(GLenum*)args->a5,
			(GLchar*)args->a6);
		break;
	case glfnGetAttachedShaders:
		glGetAttachedShaders((GLuint)args->a0, (GLsizei)args->a1, (GLsizei*)args->a2, (GLuint*)args->a3);
		break;
	case glfnGetAttribLocation:
		ret = glGetAttribLocation((GLint)args->a0, (GLchar*)args->a1);
		free((void*)args->a1);
		break;
	case glfnGetBooleanv:
		glGetBooleanv((GLenum)args->a0, (GLboolean*)args->a1);
		break;
	case glfnGetBufferParameteri:
		glGetBufferParameteriv((GLenum)args->a0, (GLenum)args->a1, (GLint*)&ret);
		break;
	case glfnGetFloatv:
		glGetFloatv((GLenum)args->a0, (GLfloat*)args->a1);
		break;
	case glfnGetIntegerv:
		glGetIntegerv((GLenum)args->a0, (GLint*)args->a1);
		break;
	case glfnGetError:
		ret = glGetError();
		break;
	case glfnGetFramebufferAttachmentParameteriv:
		glGetFramebufferAttachmentParameteriv((GLenum)args->a0, (GLenum)args->a1, (GLenum)args->a2, (GLint*)&ret);
		break;
	case glfnGetProgramiv:
		glGetProgramiv((GLint)args->a0, (GLenum)args->a1, (GLint*)&ret);
		break;
	case glfnGetProgramInfoLog:
		glGetProgramInfoLog((GLuint)args->a0, (GLsizei)args->a1, (GLsizei*)args->a2, (GLchar*)args->a3);
		break;
	case glfnGetRenderbufferParameteriv:
		glGetRenderbufferParameteriv((GLenum)args->a0, (GLenum)args->a1, (GLint*)&ret);
		break;
	case glfnGetShaderiv:
		glGetShaderiv((GLint)args->a0, (GLenum)args->a1, (GLint*)&ret);
		break;
	case glfnGetShaderInfoLog:
		glGetShaderInfoLog((GLuint)args->a0, (GLsizei)args->a1, (GLsizei*)args->a2, (GLchar*)args->a3);
		break;
	case glfnGetShaderPrecisionFormat:
		glGetShaderPrecisionFormat((GLenum)args->a0, (GLenum)args->a1, (GLint*)args->a2, (GLint*)args->a3);
		break;
	case glfnGetShaderSource:
		glGetShaderSource((GLuint)args->a0, (GLsizei)args->a1, (GLsizei*)args->a2, (GLchar*)args->a3);
		break;
	case glfnGetString:
		ret = (uintptr_t)glGetString((GLenum)args->a0);
		break;
	case glfnGetTexParameterfv:
		glGetTexParameterfv((GLenum)args->a0, (GLenum)args->a1, (GLfloat*)args->a2);
		break;
	case glfnGetTexParameteriv:
		glGetTexParameteriv((GLenum)args->a0, (GLenum)args->a1, (GLint*)args->a2);
		break;
	case glfnGetUniformfv:
		glGetUniformfv((GLuint)args->a0, (GLint)args->a1, (GLfloat*)args->a2);
		break;
	case glfnGetUniformiv:
		glGetUniformiv((GLuint)args->a0, (GLint)args->a1, (GLint*)args->a2);
		break;
	case glfnGetUniformLocation:
		ret = glGetUniformLocation((GLint)args->a0, (GLchar*)args->a1);
		free((void*)args->a1);
		break;
	case glfnGetVertexAttribfv:
		glGetVertexAttribfv((GLuint)args->a0, (GLenum)args->a1, (GLfloat*)args->a2);
		break;
	case glfnGetVertexAttribiv:
		glGetVertexAttribiv((GLuint)args->a0, (GLenum)args->a1, (GLint*)args->a2);
		break;
	case glfnHint:
		glHint((GLenum)args->a0, (GLenum)args->a1);
		break;
	case glfnIsBuffer:
		ret = glIsBuffer((GLint)args->a0);
		break;
	case glfnIsEnabled:
		ret = glIsEnabled((GLenum)args->a0);
		break;
	case glfnIsFramebuffer:
		ret = glIsFramebuffer((GLint)args->a0);
		break;
	case glfnIsProgram:
		ret = glIsProgram((GLint)args->a0);
		break;
	case glfnIsRenderbuffer:
		ret = glIsRenderbuffer((GLint)args->a0);
		break;
	case glfnIsShader:
		ret = glIsShader((GLint)args->a0);
		break;
	case glfnIsTexture:
		ret = glIsTexture((GLint)args->a0);
		break;
	case glfnLineWidth:
		glLineWidth(*(GLfloat*)&args->a0);
		break;
	case glfnLinkProgram:
		glLinkProgram((GLint)args->a0);
		break;
	case glfnPixelStorei:
		glPixelStorei((GLenum)args->a0, (GLint)args->a1);
		break;
	case glfnPolygonOffset:
		glPolygonOffset(*(GLfloat*)&args->a0, *(GLfloat*)&args->a1);
		break;
	case glfnReadPixels:
		glReadPixels((GLint)args->a0, (GLint)args->a1, (GLsizei)args->a2, (GLsizei)args->a3, (GLenum)args->a4, (GLenum)args->a5, (void*)args->a6);
		break;
	case glfnReleaseShaderCompiler:
		glReleaseShaderCompiler();
		break;
	case glfnRenderbufferStorage:
		glRenderbufferStorage((GLenum)args->a0, (GLenum)args->a1, (GLint)args->a2, (GLint)args->a3);
		break;
	case glfnSampleCoverage:
		glSampleCoverage(*(GLfloat*)&args->a0, (GLboolean)args->a1);
		break;
	case glfnScissor:
		glScissor((GLint)args->a0, (GLint)args->a1, (GLint)args->a2, (GLint)args->a3);
		break;
	case glfnShaderSource:
#if defined(os_ios) || defined(os_osx)
		glShaderSource((GLuint)args->a0, (GLsizei)args->a1, (const GLchar *const *)args->a2, NULL);
#else
		glShaderSource((GLuint)args->a0, (GLsizei)args->a1, (const GLchar **)args->a2, NULL);
#endif
		free(*(void**)args->a2);
		free((void*)args->a2);
		break;
	case glfnStencilFunc:
		glStencilFunc((GLenum)args->a0, (GLint)args->a1, (GLuint)args->a2);
		break;
	case glfnStencilFuncSeparate:
		glStencilFuncSeparate((GLenum)args->a0, (GLenum)args->a1, (GLint)args->a2, (GLuint)args->a3);
		break;
	case glfnStencilMask:
		glStencilMask((GLuint)args->a0);
		break;
	case glfnStencilMaskSeparate:
		glStencilMaskSeparate((GLenum)args->a0, (GLuint)args->a1);
		break;
	case glfnStencilOp:
		glStencilOp((GLenum)args->a0, (GLenum)args->a1, (GLenum)args->a2);
		break;
	case glfnStencilOpSeparate:
		glStencilOpSeparate((GLenum)args->a0, (GLenum)args->a1, (GLenum)args->a2, (GLenum)args->a3);
		break;
	case glfnTexImage2D:
		glTexImage2D(
			(GLenum)args->a0,
			(GLint)args->a1,
			(GLint)args->a2,
			(GLsizei)args->a3,
			(GLsizei)args->a4,
			0, // border
			(GLenum)args->a5,
			(GLenum)args->a6,
			(const GLvoid*)args->a7);
		break;
	case glfnTexSubImage2D:
		glTexSubImage2D(
			(GLenum)args->a0,
			(GLint)args->a1,
			(GLint)args->a2,
			(GLint)args->a3,
			(GLsizei)args->a4,
			(GLsizei)args->a5,
			(GLenum)args->a6,
			(GLenum)args->a7,
			(const GLvoid*)args->a8);
		break;
	case glfnTexParameterf:
		glTexParameterf((GLenum)args->a0, (GLenum)args->a1, *(GLfloat*)&args->a2);
		break;
	case glfnTexParameterfv:
		glTexParameterfv((GLenum)args->a0, (GLenum)args->a1, (GLfloat*)args->a2);
		break;
	case glfnTexParameteri:
		glTexParameteri((GLenum)args->a0, (GLenum)args->a1, (GLint)args->a2);
		break;
	case glfnTexParameteriv:
		glTexParameteriv((GLenum)args->a0, (GLenum)args->a1, (GLint*)args->a2);
		break;
	case glfnUniform1f:
		glUniform1f((GLint)args->a0, *(GLfloat*)&args->a1);
		break;
	case glfnUniform1fv:
		glUniform1fv((GLint)args->a0, (GLsizeiptr)args->a1, (GLvoid*)args->a2);
		break;
	case glfnUniform1i:
		glUniform1i((GLint)args->a0, (GLint)args->a1);
		break;
	case glfnUniform1iv:
		glUniform1iv((GLint)args->a0, (GLsizeiptr)args->a1, (GLvoid*)args->a2);
		break;
	case glfnUniform2f:
		glUniform2f((GLint)args->a0, *(GLfloat*)&args->a1, *(GLfloat*)&args->a2);
		break;
	case glfnUniform2fv:
		glUniform2fv((GLint)args->a0, (GLsizeiptr)args->a1, (GLvoid*)args->a2);
		break;
	case glfnUniform2i:
		glUniform2i((GLint)args->a0, (GLint)args->a1, (GLint)args->a2);
		break;
	case glfnUniform2iv:
		glUniform2iv((GLint)args->a0, (GLsizeiptr)args->a1, (GLvoid*)args->a2);
		break;
	case glfnUniform3f:
		glUniform3f((GLint)args->a0, *(GLfloat*)&args->a1, *(GLfloat*)&args->a2, *(GLfloat*)&args->a3);
		break;
	case glfnUniform3fv:
		glUniform3fv((GLint)args->a0, (GLsizeiptr)args->a1, (GLvoid*)args->a2);
		break;
	case glfnUniform3i:
		glUniform3i((GLint)args->a0, (GLint)args->a1, (GLint)args->a2, (GLint)args->a3);
		break;
	case glfnUniform3iv:
		glUniform3iv((GLint)args->a0, (GLsizeiptr)args->a1, (GLvoid*)args->a2);
		break;
	case glfnUniform4f:
		glUniform4f((GLint)args->a0, *(GLfloat*)&args->a1, *(GLfloat*)&args->a2, *(GLfloat*)&args->a3, *(GLfloat*)&args->a4);
		break;
	case glfnUniform4fv:
		glUniform4fv((GLint)args->a0, (GLsizeiptr)args->a1, (GLvoid*)args->a2);
		break;
	case glfnUniform4i:
		glUniform4i((GLint)args->a0, (GLint)args->a1, (GLint)args->a2, (GLint)args->a3, (GLint)args->a4);
		break;
	case glfnUniform4iv:
		glUniform4iv((GLint)args->a0, (GLsizeiptr)args->a1, (GLvoid*)args->a2);
		break;
	case glfnUniformMatrix2fv:
		glUniformMatrix2fv((GLint)args->a0, (GLsizeiptr)args->a1, 0, (GLvoid*)args->a2);
		break;
	case glfnUniformMatrix3fv:
		glUniformMatrix3fv((GLint)args->a0, (GLsizeiptr)args->a1, 0, (GLvoid*)args->a2);
		break;
	case glfnUniformMatrix4fv:
		glUniformMatrix4fv((GLint)args->a0, (GLsizeiptr)args->a1, 0, (GLvoid*)args->a2);
		break;
	case glfnUseProgram:
		glUseProgram((GLint)args->a0);
		break;
	case glfnValidateProgram:
		glValidateProgram((GLint)args->a0);
		break;
	case glfnVertexAttrib1f:
		glVertexAttrib1f((GLint)args->a0, *(GLfloat*)&args->a1);
		break;
	case glfnVertexAttrib1fv:
		glVertexAttrib1fv((GLint)args->a0, (GLfloat*)args->a1);
		break;
	case glfnVertexAttrib2f:
		glVertexAttrib2f((GLint)args->a0, *(GLfloat*)&args->a1, *(GLfloat*)&args->a2);
		break;
	case glfnVertexAttrib2fv:
		glVertexAttrib2fv((GLint)args->a0, (GLfloat*)args->a1);
		break;
	case glfnVertexAttrib3f:
		glVertexAttrib3f((GLint)args->a0, *(GLfloat*)&args->a1, *(GLfloat*)&args->a2, *(GLfloat*)&args->a3);
		break;
	case glfnVertexAttrib3fv:
		glVertexAttrib3fv((GLint)args->a0, (GLfloat*)args->a1);
		break;
	case glfnVertexAttrib4f:
		glVertexAttrib4f((GLint)args->a0, *(GLfloat*)&args->a1, *(GLfloat*)&args->a2, *(GLfloat*)&args->a3, *(GLfloat*)&args->a4);
		break;
	case glfnVertexAttrib4fv:
		glVertexAttrib4fv((GLint)args->a0, (GLfloat*)args->a1);
		break;
	case glfnVertexAttribPointer:
		glVertexAttribPointer((GLuint)args->a0, (GLint)args->a1, (GLenum)args->a2, (GLboolean)args->a3, (GLsizei)args->a4, (const GLvoid*)args->a5);
		break;
	case glfnViewport:
		glViewport((GLint)args->a0, (GLint)args->a1, (GLint)args->a2, (GLint)args->a3);
		break;
	}
}
Exemplo n.º 23
0
	UINT ShaderGL::CreateFromMemory(char* source)
	{
		mSource = source;

		mProgram = glCreateProgram();

		if (mProgram < 0)
		{
			Debug::ShowError(
				"Could not create shader program.",
				"Shader Loader Error");
		}

		
		if (strstr(mSource, "VERTEX_SHADER") != nullptr)
		{
			const char *vshader[2] = { "#version 330\n#define VERSION_GL\n#define VERTEX_SHADER\n\0", mSource };

			if (!Compile(vshader, mVertexShader, GL_VERTEX_SHADER, 2))
				return S_FALSE;

			glAttachShader(mProgram, mVertexShader);
		}

		
		if (strstr(mSource, "GEOMETRY_SHADER") != nullptr)
		{
			const char *gshader[2] = { "#version 330\n#define VERSION_GL\n#define GEOMETRY_SHADER\n\0", mSource };

			if (!Compile(gshader, mGeometryShader, GL_GEOMETRY_SHADER, 2))
				return S_FALSE;

			glAttachShader(mProgram, mGeometryShader);
		}

		
		if (strstr(mSource, "FRAGMENT_SHADER") != nullptr)
		{
			const char *fshader[2] = { "#version 330\n#define VERSION_GL\n#define FRAGMENT_SHADER\n\0", mSource };

			if (!Compile(fshader, mFragmentShader, GL_FRAGMENT_SHADER, 2))
				return S_FALSE;

			glAttachShader(mProgram, mFragmentShader);
		}

		Debug::Log("Shader Compiled Successfully!");

		
		int didCompile;

		glLinkProgram(mProgram);
		glGetProgramiv(mProgram, GL_LINK_STATUS, &didCompile);

		if (didCompile == GL_FALSE)
		{
			char* compileLog;
			int length;

			glGetProgramiv(mProgram, GL_INFO_LOG_LENGTH, &length);

			compileLog = (char*)malloc(length);

			glGetProgramInfoLog(mProgram, length, &length, compileLog);

			Debug::Log("\nLink Shader Log");
			Debug::Log(compileLog);

			free(compileLog);

			Release();

			return S_FALSE;
		}

		CreateAttribute("Position", VertexAttribute::POSITION);
		CreateAttribute("TexCoord0", VertexAttribute::TEXCOORD0);
		CreateAttribute("TexCoord1", VertexAttribute::TEXCOORD1);
		CreateAttribute("TexCoord2", VertexAttribute::TEXCOORD2);
		CreateAttribute("QuadCoord0", VertexAttribute::QUADCOORD0);
		CreateAttribute("QuadCoord1", VertexAttribute::QUADCOORD1);
		CreateAttribute("QuadCoord2", VertexAttribute::QUADCOORD2);
		CreateAttribute("Normal", VertexAttribute::NORMAL);
		CreateAttribute("Color", VertexAttribute::COLOR);
		CreateAttribute("Tangent", VertexAttribute::TANGENT);
		CreateAttribute("BoneCount", VertexAttribute::BONE_COUNT);
		CreateAttribute("BoneMatrix", VertexAttribute::BONE_INDEX);
		CreateAttribute("BoneWeight", VertexAttribute::BONE_WEIGHT);

		if (CreateAttribute("Matrix", VertexAttribute::MATRIX))
			mAttributeSize += 3;

		VertexLayoutGL* layout = new VertexLayoutGL();

		UINT size = (UINT)mAttributes.size();
		for (UINT x = 0; x < size; ++x)
		{
			layout->AddAttribute(mAttributes[x]);
		}

		mLayout = std::shared_ptr< VertexLayout >(layout);

		CreateUniform("_WorldViewProj", ShaderUniform::WORLD_VIEW_PROJ);
		CreateUniform("_WorldView", ShaderUniform::WORLD_VIEW);
		CreateUniform("_World", ShaderUniform::WORLD);
		CreateUniform("_InvWorld", ShaderUniform::INV_WORLD);
		CreateUniform("_View", ShaderUniform::VIEW);
		CreateUniform("_InvView", ShaderUniform::INV_VIEW);
		CreateUniform("_Proj", ShaderUniform::PROJ);
		CreateUniform("_InvProj", ShaderUniform::INV_PROJ);
		CreateUniform("_Ambient", ShaderUniform::AMBIENT);
		CreateUniform("_Diffuse", ShaderUniform::DIFFUSE);
		CreateUniform("_Specular", ShaderUniform::SPECULAR);
		CreateUniform("_SpecComp", ShaderUniform::SPEC_COMP);
		CreateUniform("_LightPos", ShaderUniform::LIGHT_POS);
		CreateUniform("_LightDir", ShaderUniform::LIGHT_DIR);
		CreateUniform("_LightColor", ShaderUniform::LIGHT_COLOR);
		CreateUniform("_LightAttn", ShaderUniform::LIGHT_ATTN);
		CreateUniform("_LightMatrix", ShaderUniform::LIGHT_MATRIX);
		CreateUniform("_LightCubeMatrix", ShaderUniform::LIGHT_CUBE_MATRIX);
		CreateUniform("_CameraPos", ShaderUniform::CAMERA_POS);
		CreateUniform("_Bones", ShaderUniform::BONES);
		CreateUniform("_DeltaTime", ShaderUniform::DELTA_TIME);

		UINT numTextureCube = 0;
		if (CreateUniform("_TextureCube", ShaderUniform::LIGHT_TEXTURE_CUBE))
			++numTextureCube;

		UINT numTexture = 0;
		char texName[16];
		for (int x = 0; x < MAX_TEXTURES; ++x)
		{
			sprintf_s(texName, "_Texture%d", x);

			if (CreateUniform(texName, ShaderUniform::TEXTURE))
				++numTexture;
		}

		mNumSamplers = numTexture + numTextureCube;

		if (mNumSamplers > 0)
		{
			mSampler = new Sampler*[mNumSamplers];

			UINT index = 0;

			for (; index < numTextureCube; ++index)
				mSampler[index] = new SamplerCubeGL();

			for (; index < mNumSamplers; ++index)
				mSampler[index] = new SamplerGL();
		}

		Debug::Log("Shader Created Successfully!");

		return S_OK;
	}
void QSGSharedDistanceFieldGlyphCache::saveTexture(GLuint textureId, int width, int height)
{
    GLuint fboId;
    glGenFramebuffers(1, &fboId);

    GLuint tmpTexture = 0;
    glGenTextures(1, &tmpTexture);
    glBindTexture(GL_TEXTURE_2D, tmpTexture);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glBindTexture(GL_TEXTURE_2D, 0);

    glBindFramebuffer(GL_FRAMEBUFFER_EXT, fboId);
    glFramebufferTexture2D(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D,
                           tmpTexture, 0);

    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, textureId);

    glDisable(GL_STENCIL_TEST);
    glDisable(GL_DEPTH_TEST);
    glDisable(GL_SCISSOR_TEST);
    glDisable(GL_BLEND);

    GLfloat textureCoordinateArray[8];
    textureCoordinateArray[0] = 0.0f;
    textureCoordinateArray[1] = 0.0f;
    textureCoordinateArray[2] = 1.0f;
    textureCoordinateArray[3] = 0.0f;
    textureCoordinateArray[4] = 1.0f;
    textureCoordinateArray[5] = 1.0f;
    textureCoordinateArray[6] = 0.0f;
    textureCoordinateArray[7] = 1.0f;

    GLfloat vertexCoordinateArray[8];
    vertexCoordinateArray[0] = -1.0f;
    vertexCoordinateArray[1] = -1.0f;
    vertexCoordinateArray[2] =  1.0f;
    vertexCoordinateArray[3] = -1.0f;
    vertexCoordinateArray[4] =  1.0f;
    vertexCoordinateArray[5] =  1.0f;
    vertexCoordinateArray[6] = -1.0f;
    vertexCoordinateArray[7] =  1.0f;

    glViewport(0, 0, width, height);
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, vertexCoordinateArray);
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, textureCoordinateArray);

    {
        static const char vertexShaderSource[] =
                "attribute highp   vec4      vertexCoordsArray; \n"
                "attribute highp   vec2      textureCoordArray; \n"
                "varying   highp   vec2      textureCoords;     \n"
                "void main(void) \n"
                "{ \n"
                "    gl_Position = vertexCoordsArray;   \n"
                "    textureCoords = textureCoordArray; \n"
                "} \n";

        static const char fragmentShaderSource[] =
                "varying   highp   vec2      textureCoords; \n"
                "uniform   sampler2D         texture;       \n"
                "void main() \n"
                "{ \n"
                "    gl_FragColor = texture2D(texture, textureCoords); \n"
                "} \n";

        GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
        GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);

        if (vertexShader == 0 || fragmentShader == 0) {
            GLenum error = glGetError();
            qWarning("SharedGraphicsCacheServer::setupShaderPrograms: Failed to create shaders. (GL error: %x)",
                     error);
            return;
        }

        glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
        glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
        glCompileShader(vertexShader);

        GLint len = 1;
        glGetShaderiv(vertexShader, GL_INFO_LOG_LENGTH, &len);

        char infoLog[2048];
        glGetShaderInfoLog(vertexShader, 2048, NULL, infoLog);
        if (qstrlen(infoLog) > 0) {
            qWarning("SharedGraphicsCacheServer::setupShaderPrograms, problems compiling vertex shader:\n %s",
                     infoLog);
            //return;
        }

        glCompileShader(fragmentShader);
        glGetShaderInfoLog(fragmentShader, 2048, NULL, infoLog);
        if (qstrlen(infoLog) > 0) {
            qWarning("SharedGraphicsCacheServer::setupShaderPrograms, problems compiling fragent shader:\n %s",
                     infoLog);
            //return;
        }

        GLuint shaderProgram = glCreateProgram();
        glAttachShader(shaderProgram, vertexShader);
        glAttachShader(shaderProgram, fragmentShader);

        glBindAttribLocation(shaderProgram, 0, "vertexCoordsArray");
        glBindAttribLocation(shaderProgram, 1, "textureCoordArray");

        glLinkProgram(shaderProgram);
        glGetProgramInfoLog(shaderProgram, 2048, NULL, infoLog);
        if (qstrlen(infoLog) > 0) {
            qWarning("SharedGraphicsCacheServer::setupShaderPrograms, problems linking shaders:\n %s",
                     infoLog);
            //return;
        }

        glUseProgram(shaderProgram);
        glEnableVertexAttribArray(0);
        glEnableVertexAttribArray(1);

        int textureUniformLocation = glGetUniformLocation(shaderProgram, "_qt_texture");
        glUniform1i(textureUniformLocation, 0);
    }

    glDrawArrays(GL_TRIANGLE_FAN, 0, 4);

    {
        GLenum error = glGetError();
        if (error != GL_NO_ERROR) {
            qWarning("SharedGraphicsCacheServer::readBackBuffer: glDrawArrays reported error 0x%x",
                     error);
        }
    }

    uchar *data = new uchar[width * height * 4];

    glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, data);

    QImage image(width, height, QImage::Format_ARGB32);
    quint32 *dest = reinterpret_cast<quint32 *>(image.bits());
    for (int i=0; i<width*height; ++i)
        dest[i] = qRgba(0xff, 0xff, 0xff, data[i]);

    QByteArray fileName = m_cacheId + ' ' + QByteArray::number(textureId);
    fileName = fileName.replace('/', '_').replace(' ', '_') + ".png";
    image.save(QString::fromLocal8Bit(fileName));

    {
        GLenum error = glGetError();
        if (error != GL_NO_ERROR) {
            qWarning("SharedGraphicsCacheServer::readBackBuffer: glReadPixels reported error 0x%x",
                     error);
        }
    }

    glDisableVertexAttribArray(0);
    glDisableVertexAttribArray(1);

    glDeleteFramebuffers(1, &fboId);
    glDeleteTextures(1, &tmpTexture);

    delete[] data;
}
Exemplo n.º 25
0
int Mesh::loadShaders(const char* vertexFile, const char* fragmentFile)
{
	GLint result = GL_FALSE;
	int infoLogLength;
	GLuint vertexShaderID = glCreateShader(GL_VERTEX_SHADER);
	GLuint fragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER);

	std::ofstream outputLog("output.txt", std::ios::out);

	std::string vertexShaderCode;
	std::ifstream vertexShaderStream(vertexFile, std::ios::in);
	if(vertexShaderStream.is_open())
	{
		char line[256];
		while(vertexShaderStream.getline(line, 256))
		{
			vertexShaderCode += std::string("\n");
			vertexShaderCode += std::string(line);
		}
		vertexShaderStream.close();
	}
	const char* vertexShaderSource = vertexShaderCode.c_str();

	// Compile vertex shader
	glShaderSource(vertexShaderID, 1, &vertexShaderSource, NULL);
	glCompileShader(vertexShaderID);

	// Check vertex shader
	glGetShaderiv(vertexShaderID, GL_COMPILE_STATUS, &result);
	glGetShaderiv(vertexShaderID, GL_INFO_LOG_LENGTH, &infoLogLength);
	std::vector<char> vertexShaderErrorMessage(infoLogLength);
	glGetShaderInfoLog(vertexShaderID, infoLogLength, NULL, &vertexShaderErrorMessage[0]);
	
	if(outputLog.is_open())
	{
		outputLog<<&vertexShaderErrorMessage[0]<<std::endl;
	}

	std::string fragmentShaderCode;
	std::ifstream fragmentShaderStream(fragmentFile, std::ios::in);
	if(fragmentShaderStream.is_open())
	{
		char line[256];
		while(fragmentShaderStream.getline(line, 256))
		{
			fragmentShaderCode += std::string("\n");
			fragmentShaderCode += std::string(line);
		}
		fragmentShaderStream.close();
	}
	const char* fragmentShaderSource = fragmentShaderCode.c_str();

	// Compile fragment shader
	glShaderSource(fragmentShaderID, 1, &fragmentShaderSource, NULL);
	glCompileShader(fragmentShaderID);

	// Check fragment shader
	glGetShaderiv(fragmentShaderID, GL_COMPILE_STATUS, &result);
	glGetShaderiv(fragmentShaderID, GL_INFO_LOG_LENGTH, &infoLogLength);
	std::vector<char> fragmentShaderErrorMessage(infoLogLength);
	glGetShaderInfoLog(fragmentShaderID, infoLogLength, NULL, &fragmentShaderErrorMessage[0]);
	
	if(outputLog.is_open())
	{
		outputLog<<&fragmentShaderErrorMessage[0]<<std::endl;
	}

	// Create and link a program
	GLuint programID = glCreateProgram();
	glAttachShader(programID, vertexShaderID);
	glAttachShader(programID, fragmentShaderID);
	glLinkProgram(programID);

	// Check the program
	glGetProgramiv(programID, GL_LINK_STATUS, &result);
	glGetProgramiv(programID, GL_INFO_LOG_LENGTH, &infoLogLength);
	std::vector<char> programErrorMessage(infoLogLength);
	glGetProgramInfoLog(programID, infoLogLength, NULL, &programErrorMessage[0]);
	
	if(outputLog.is_open())
	{
		outputLog<<&programErrorMessage[0]<<std::endl;
	}

	outputLog.close();

	glDeleteShader(vertexShaderID);
	glDeleteShader(fragmentShaderID);

	return programID;
}
Exemplo n.º 26
0
int main(void)
{
    GLFWwindow* window;

    /* Initialize the library */
    if (!glfwInit())
        return -1;

    /* Create a windowed mode window and its OpenGL context */
    window = glfwCreateWindow(800, 450, "Mah Base Project", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        return -1;
    }

    /* Make the window's context current */
    glfwMakeContextCurrent(window);

    glewExperimental = GL_TRUE;
    glewInit();
    // Create Vertex Array Object
    GLuint vao;
    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);
    // Create a Vertex Buffer Object and copy the vertex data to it
    GLuint vbo;
    glGenBuffers(1, &vbo);
    GLfloat vertices[] = {
        0.0f, 0.5f,
        0.5f, -0.5f,
        -0.5f, -0.5f
    };
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    const char* vertexSource = loadSource("VertexSource.glsl");

    const char* fragmentSource = loadSource("FragmentSource.glsl");

    GLint status = GL_TRUE;

    GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vertexShader, 1, &vertexSource, NULL);
    glCompileShader(vertexShader);
    glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &status);
    // cout<< "Vertex" << status << endl;

    // Create and compile the fragment shader
    GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragmentShader, 1, &fragmentSource, NULL);
    glCompileShader(fragmentShader);
    glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &status);
    // cout<< "Fragment" << status << endl;

    // Link the vertex and fragment shader into a shader program
    GLuint shaderProgram = glCreateProgram();
    glAttachShader(shaderProgram, vertexShader);
    glAttachShader(shaderProgram, fragmentShader);
    glBindFragDataLocation(shaderProgram, 0, "outColor");
    glLinkProgram(shaderProgram);
    glUseProgram(shaderProgram);

    // Specify the layout of the vertex data
    GLint posAttrib = glGetAttribLocation(shaderProgram, "position");
    glEnableVertexAttribArray(posAttrib);
    glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, 0, 0);


    /* Loop until the user closes the window */
    while (!glfwWindowShouldClose(window))
    {
        /* Render here */
        // Clear the screen to black
        glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);
        // Draw a triangle from the 3 vertices
        glDrawArrays(GL_TRIANGLES, 0, 3);
        // Swap buffers

        /* Swap front and back buffers */
        glfwSwapBuffers(window);

        /* Poll for and process events */
        glfwPollEvents();
    }

    glfwTerminate();
    return 0;
}
Exemplo n.º 27
0
// Alternative single C++ method to Load/Compile/Link a pair for vertex and fragment shaders
GLuint LoadShaders(const char * vertex_file_path,const char * fragment_file_path)
{


	string str_vertex_filepath = getGLSLResourcePath(vertex_file_path);
	//cout << str_vertex_filepath << endl;
	string str_fragment_filepath = getGLSLResourcePath(fragment_file_path);
	//cout << str_fragment_filepath << endl;


	// Create the shaders
	GLuint VertexShaderID = glCreateShader(GL_VERTEX_SHADER);
	GLuint FragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER);

	// Read the Vertex Shader code from the file
	std::string VertexShaderCode;
	std::ifstream VertexShaderStream(str_vertex_filepath.c_str(), std::ios::in);
	if(VertexShaderStream.is_open()){
		std::string Line = "";
		while(getline(VertexShaderStream, Line))
			VertexShaderCode += "\n" + Line;
		VertexShaderStream.close();
	}
	else
	{
		std::cout<<"shader: "<<str_vertex_filepath<<" not found!"<<std::endl;
		return 0;
	}

	// Read the Fragment Shader code from the file
	std::string FragmentShaderCode;
	std::ifstream FragmentShaderStream(str_fragment_filepath.c_str(), std::ios::in);
	if(FragmentShaderStream.is_open()){
		std::string Line = "";
		while(getline(FragmentShaderStream, Line))
			FragmentShaderCode += "\n" + Line;
		FragmentShaderStream.close();
	}
	else
	{
		std::cout<<"shader: "<<str_fragment_filepath<<" not found!"<<std::endl;
		return 0;
	}

	GLint Result = GL_FALSE;
	int InfoLogLength=10;

	// Compile Vertex Shader
	printf("Compiling shader : %s\n\n", str_vertex_filepath.c_str());
	char const * VertexSourcePointer = VertexShaderCode.c_str();
	glShaderSource(VertexShaderID, 1, &VertexSourcePointer , NULL);
	glCompileShader(VertexShaderID);

	// Check Vertex Shader
	glGetShaderiv(VertexShaderID, GL_COMPILE_STATUS, &Result);
	if (!Result) 
	{
		glGetShaderiv(VertexShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength);
		std::vector<char> VertexShaderErrorMessage(InfoLogLength);
		glGetShaderInfoLog(VertexShaderID, InfoLogLength, NULL, &VertexShaderErrorMessage[0]);
		fprintf(stdout, "%s\n", &VertexShaderErrorMessage[0]);
	}
	// Compile Fragment Shader
	printf("Compiling shader : %s\n\n", str_fragment_filepath.c_str());
	char const * FragmentSourcePointer = FragmentShaderCode.c_str();
	glShaderSource(FragmentShaderID, 1, &FragmentSourcePointer , NULL);
	glCompileShader(FragmentShaderID);

	// Check Fragment Shader
	glGetShaderiv(FragmentShaderID, GL_COMPILE_STATUS, &Result);
	if (!Result) 
	{
		glGetShaderiv(FragmentShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength);
		std::vector<char> FragmentShaderErrorMessage(InfoLogLength);
		glGetShaderInfoLog(FragmentShaderID, InfoLogLength, NULL, &FragmentShaderErrorMessage[0]);
		fprintf(stdout, "%s\n", &FragmentShaderErrorMessage[0]);
	}
	// Link the program
	fprintf(stdout, "Linking program\n");
	GLuint ProgramID = glCreateProgram();
	glAttachShader(ProgramID, VertexShaderID);
	glAttachShader(ProgramID, FragmentShaderID);
	glLinkProgram(ProgramID);

	// Check the program
	glGetProgramiv(ProgramID, GL_LINK_STATUS, &Result);
	glGetProgramiv(ProgramID, GL_INFO_LOG_LENGTH, &InfoLogLength);
	std::vector<char> ProgramErrorMessage( max(InfoLogLength, int(1)) );
	glGetProgramInfoLog(ProgramID, InfoLogLength, NULL, &ProgramErrorMessage[0]);
	fprintf(stdout, "%s\n", &ProgramErrorMessage[0]);


	glDeleteShader(VertexShaderID);
	glDeleteShader(FragmentShaderID);

	return ProgramID;
}
Exemplo n.º 28
0
bool ImGui_ImplSdlGL3_CreateDeviceObjects()
{
	// Backup GL state
	GLint last_texture, last_array_buffer, last_vertex_array;
	glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
	glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer);
	glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array);

	const GLchar *vertex_shader =
		"#version 330\n"
		"uniform mat4 ProjMtx;\n"
		"in vec2 Position;\n"
		"in vec2 UV;\n"
		"in vec4 Color;\n"
		"out vec2 Frag_UV;\n"
		"out vec4 Frag_Color;\n"
		"void main()\n"
		"{\n"
		"	Frag_UV = UV;\n"
		"	Frag_Color = Color;\n"
		"	gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
		"}\n";

	const GLchar* fragment_shader =
		"#version 330\n"
		"uniform sampler2D Texture;\n"
		"in vec2 Frag_UV;\n"
		"in vec4 Frag_Color;\n"
		"out vec4 Out_Color;\n"
		"void main()\n"
		"{\n"
		"	Out_Color = Frag_Color * texture( Texture, Frag_UV.st);\n"
		"}\n";

	g_ShaderHandle = glCreateProgram();
	g_VertHandle = glCreateShader(GL_VERTEX_SHADER);
	g_FragHandle = glCreateShader(GL_FRAGMENT_SHADER);
	glShaderSource(g_VertHandle, 1, &vertex_shader, 0);
	glShaderSource(g_FragHandle, 1, &fragment_shader, 0);
	glCompileShader(g_VertHandle);
	glCompileShader(g_FragHandle);
	glAttachShader(g_ShaderHandle, g_VertHandle);
	glAttachShader(g_ShaderHandle, g_FragHandle);
	glLinkProgram(g_ShaderHandle);

	g_AttribLocationTex = glGetUniformLocation(g_ShaderHandle, "Texture");
	g_AttribLocationProjMtx = glGetUniformLocation(g_ShaderHandle, "ProjMtx");
	g_AttribLocationPosition = glGetAttribLocation(g_ShaderHandle, "Position");
	g_AttribLocationUV = glGetAttribLocation(g_ShaderHandle, "UV");
	g_AttribLocationColor = glGetAttribLocation(g_ShaderHandle, "Color");

	glGenBuffers(1, &g_VboHandle);
	glGenBuffers(1, &g_ElementsHandle);

	glGenVertexArrays(1, &g_VaoHandle);
	glBindVertexArray(g_VaoHandle);
	glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle);
	glEnableVertexAttribArray(g_AttribLocationPosition);
	glEnableVertexAttribArray(g_AttribLocationUV);
	glEnableVertexAttribArray(g_AttribLocationColor);

#define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT))
	glVertexAttribPointer(g_AttribLocationPosition, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, pos));
	glVertexAttribPointer(g_AttribLocationUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, uv));
	glVertexAttribPointer(g_AttribLocationColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, col));
#undef OFFSETOF

	ImGui_ImplSdlGL3_CreateFontsTexture();

	// Restore modified GL state
	glBindTexture(GL_TEXTURE_2D, last_texture);
	glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer);
	glBindVertexArray(last_vertex_array);

	return true;
}
Exemplo n.º 29
0
GLuint	compile_shaders(void)
{
	GLuint	vertex_shader;
	GLuint	fragment_shader;
	GLuint	program;
	static const GLchar	*vertex_shader_source[] =
		{
			"#version 410 core													\n"
			"																	\n"
			"in vec3 vertices;													\n"
			"layout (location = 1) in vec3 color;								\n"
			"																	\n"
			"uniform mat4 projection;											\n"
			"uniform mat4 modelview;											\n"
			"																	\n"
			"out vec3 fragmentColor;											\n"
			"																	\n"
			"void main(void)													\n"
			"{																	\n"
			"	gl_Position = projection * modelview * vec4(vertices, 1.0f);	\n"
			"	fragmentColor = color;											\n"
			"}																	\n"
		};
	static const GLchar	*fragment_shader_source[] =
		{
			"#version 410 core													\n"
			"																	\n"
			"in vec3 fragmentColor;												\n"
			"																	\n"
			"out vec4 out_color;												\n"
			"																	\n"
			"void main(void)													\n"
			"{																	\n"
			"	out_color = vec4(fragmentColor, 1.0f);							\n"
			"}																	\n"
		};

	// Create and compile vertex shader
	vertex_shader = glCreateShader(GL_VERTEX_SHADER);
	if (vertex_shader == 0)
		printf("Error while creating vertex shader\n");
	else
		printf("Vertex shader successfully created\n");
	glShaderSource(vertex_shader, 1, vertex_shader_source, NULL);
	glCompileShader(vertex_shader);

	// Create and compile fragment shader
	fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
	if (fragment_shader == 0)
		printf("Error while creating fragment shader\n");
	else
		printf("Fragment shader successfully created\n");
	glShaderSource(fragment_shader, 1, fragment_shader_source, NULL);
	glCompileShader(fragment_shader);
	
	// Create program, attach shaders to it, and link it
	program = glCreateProgram();
	glAttachShader(program, vertex_shader);
	glAttachShader(program, fragment_shader);

	glLinkProgram(program);

	// Delete the shaders as the program has them now
	glDeleteShader(vertex_shader);
	glDeleteShader(fragment_shader);

	return (program);
}
Exemplo n.º 30
0
int main()
{
    int width = 640;
    int height = 480;
   
    UserData userdata;
    userdata.running = true;
    
    GLWTConfig glwt_config;
    glwt_config.red_bits = 8;
    glwt_config.green_bits = 8;
    glwt_config.blue_bits = 8;
    glwt_config.alpha_bits = 8;
    glwt_config.depth_bits = 24;
    glwt_config.stencil_bits = 8;
    glwt_config.samples = 0;
    glwt_config.sample_buffers = 0;
    glwt_config.api = GLWT_API_OPENGL | GLWT_PROFILE_CORE;
    glwt_config.api_version_major = 3;
    glwt_config.api_version_minor = 3;
    
    GLWTAppCallbacks app_callbacks;
    app_callbacks.error_callback = error_callback;
    app_callbacks.userdata = &userdata;
    
    if(glwtInit(&glwt_config, &app_callbacks) != 0)
    {
        std::cerr << "failed to init GLWT" << std::endl;
        return 1;
    }
 
    GLWTWindowCallbacks win_callbacks;
    win_callbacks.close_callback = close_callback;
    win_callbacks.expose_callback = 0;
    win_callbacks.resize_callback = 0;
    win_callbacks.show_callback = 0;
    win_callbacks.focus_callback = 0;
    win_callbacks.key_callback = key_callback,
    win_callbacks.motion_callback = 0;
    win_callbacks.button_callback = 0;
    win_callbacks.mouseover_callback = 0;
    win_callbacks.userdata = &userdata;
    
    // create a window
    GLWTWindow *window = glwtWindowCreate("", width, height, &win_callbacks, 0);
    if(window == 0)
    {
        std::cerr << "failed to open window" << std::endl;
        glwtQuit();
        return 1;
    }
    
    if (glxwInit())
    {
        std::cerr << "failed to init GLXW" << std::endl;
        glwtWindowDestroy(window);
        glwtQuit();
        return 1;
    }
    
    glwtWindowShow(window, 1);
    glwtMakeCurrent(window);
    glwtSwapInterval(window, 1);
 
    // shader source code
    std::string vertex_source =
        "#version 330\n"
        "uniform mat4 ViewProjection;\n" // the projection matrix uniform
        "layout(location = 0) in vec4 vposition;\n"
        "layout(location = 1) in vec4 vcolor;\n"
        "layout(location = 2) in vec3 voffset;\n" // the per instance offset
        "out vec4 fcolor;\n"
        "void main() {\n"
        "   fcolor = vcolor;\n"
        "   gl_Position = ViewProjection*(vposition + vec4(voffset, 0));\n"
        "}\n";
        
    std::string fragment_source =
        "#version 330\n"
        "in vec4 fcolor;\n"
        "layout(location = 0) out vec4 FragColor;\n"
        "void main() {\n"
        "   FragColor = fcolor;\n"
        "}\n";
   
    // program and shader handles
    GLuint shader_program, vertex_shader, fragment_shader;
    
    // we need these to properly pass the strings
    const char *source;
    int length;
 
    // create and compiler vertex shader
    vertex_shader = glCreateShader(GL_VERTEX_SHADER);
    source = vertex_source.c_str();
    length = vertex_source.size();
    glShaderSource(vertex_shader, 1, &source, &length); 
    glCompileShader(vertex_shader);
    if(!check_shader_compile_status(vertex_shader))
    {
        return 1;
    }
 
    // create and compiler fragment shader
    fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
    source = fragment_source.c_str();
    length = fragment_source.size();
    glShaderSource(fragment_shader, 1, &source, &length);   
    glCompileShader(fragment_shader);
    if(!check_shader_compile_status(fragment_shader))
    {
        return 1;
    }
    
    // create program
    shader_program = glCreateProgram();
    
    // attach shaders
    glAttachShader(shader_program, vertex_shader);
    glAttachShader(shader_program, fragment_shader);
    
    // link the program and check for errors
    glLinkProgram(shader_program);
    check_program_link_status(shader_program);
    
    // obtain location of projection uniform
    GLint ViewProjection_location = glGetUniformLocation(shader_program, "ViewProjection");
    
    
    // vao and vbo handles
    GLuint vao, vbo, tbo, ibo;
 
    // generate and bind the vao
    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);
    
    // generate and bind the vertex buffer object
    glGenBuffers(1, &vbo);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
            
    // data for a cube
    GLfloat vertexData[] = {
    //  X     Y     Z           R     G     B
    // face 0:
       1.0f, 1.0f, 1.0f,       1.0f, 0.0f, 0.0f, // vertex 0
      -1.0f, 1.0f, 1.0f,       1.0f, 0.0f, 0.0f, // vertex 1
       1.0f,-1.0f, 1.0f,       1.0f, 0.0f, 0.0f, // vertex 2
      -1.0f,-1.0f, 1.0f,       1.0f, 0.0f, 0.0f, // vertex 3
 
    // face 1:
       1.0f, 1.0f, 1.0f,       0.0f, 1.0f, 0.0f, // vertex 0
       1.0f,-1.0f, 1.0f,       0.0f, 1.0f, 0.0f, // vertex 1
       1.0f, 1.0f,-1.0f,       0.0f, 1.0f, 0.0f, // vertex 2
       1.0f,-1.0f,-1.0f,       0.0f, 1.0f, 0.0f, // vertex 3
 
    // face 2:
       1.0f, 1.0f, 1.0f,       0.0f, 0.0f, 1.0f, // vertex 0
       1.0f, 1.0f,-1.0f,       0.0f, 0.0f, 1.0f, // vertex 1
      -1.0f, 1.0f, 1.0f,       0.0f, 0.0f, 1.0f, // vertex 2
      -1.0f, 1.0f,-1.0f,       0.0f, 0.0f, 1.0f, // vertex 3
      
    // face 3:
       1.0f, 1.0f,-1.0f,       1.0f, 1.0f, 0.0f, // vertex 0
       1.0f,-1.0f,-1.0f,       1.0f, 1.0f, 0.0f, // vertex 1
      -1.0f, 1.0f,-1.0f,       1.0f, 1.0f, 0.0f, // vertex 2
      -1.0f,-1.0f,-1.0f,       1.0f, 1.0f, 0.0f, // vertex 3
 
    // face 4:
      -1.0f, 1.0f, 1.0f,       0.0f, 1.0f, 1.0f, // vertex 0
      -1.0f, 1.0f,-1.0f,       0.0f, 1.0f, 1.0f, // vertex 1
      -1.0f,-1.0f, 1.0f,       0.0f, 1.0f, 1.0f, // vertex 2
      -1.0f,-1.0f,-1.0f,       0.0f, 1.0f, 1.0f, // vertex 3
 
    // face 5:
       1.0f,-1.0f, 1.0f,       1.0f, 0.0f, 1.0f, // vertex 0
      -1.0f,-1.0f, 1.0f,       1.0f, 0.0f, 1.0f, // vertex 1
       1.0f,-1.0f,-1.0f,       1.0f, 0.0f, 1.0f, // vertex 2
      -1.0f,-1.0f,-1.0f,       1.0f, 0.0f, 1.0f, // vertex 3
    }; // 6 faces with 4 vertices with 6 components (floats)
 
    // fill with data
    glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*6*4*6, vertexData, GL_STATIC_DRAW);
                    
           
    // set up generic attrib pointers
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6*sizeof(GLfloat), (char*)0 + 0*sizeof(GLfloat));
 
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6*sizeof(GLfloat), (char*)0 + 3*sizeof(GLfloat));
 
    
    
    
    // generate and bind the index buffer object
    glGenBuffers(1, &ibo);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
            
    GLuint indexData[] = {
        // face 0:
        0,1,2,      // first triangle
        2,1,3,      // second triangle
        // face 1:
        4,5,6,      // first triangle
        6,5,7,      // second triangle
        // face 2:
        8,9,10,     // first triangle
        10,9,11,    // second triangle
        // face 3:
        12,13,14,   // first triangle
        14,13,15,   // second triangle
        // face 4:
        16,17,18,   // first triangle
        18,17,19,   // second triangle
        // face 5:
        20,21,22,   // first triangle
        22,21,23,   // second triangle
    };
 
    // fill with data
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint)*6*2*3, indexData, GL_STATIC_DRAW);
    

    // generate and bind the vertex buffer object containing the
    // instance offsets
    glGenBuffers(1, &tbo);
    glBindBuffer(GL_ARRAY_BUFFER, tbo);
            
    // the offsets
    GLfloat translationData[] = {
                 2.0f, 2.0f, 2.0f,  // cube 0
                 2.0f, 2.0f,-2.0f,  // cube 1
                 2.0f,-2.0f, 2.0f,  // cube 2
                 2.0f,-2.0f,-2.0f,  // cube 3
                -2.0f, 2.0f, 2.0f,  // cube 4
                -2.0f, 2.0f,-2.0f,  // cube 5
                -2.0f,-2.0f, 2.0f,  // cube 6
                -2.0f,-2.0f,-2.0f,  // cube 7
    }; // 8 offsets with 3 components each
 
    // fill with data
    glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*3*8, translationData, GL_STATIC_DRAW);
                    
    // set up generic attrib pointers
    glEnableVertexAttribArray(2);
    glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 3*sizeof(GLfloat), (char*)0 + 0*sizeof(GLfloat));
    
    // a attrib divisor of 1 means that attribute 2 will advance once
    // every instance (0 would mean once per vertex) 
    glVertexAttribDivisor(2, 1);
    
    
    // "unbind" vao
    glBindVertexArray(0);
 
    
    // we are drawing 3d objects so we want depth testing
    glEnable(GL_DEPTH_TEST);
 
    while(userdata.running)
    {   
        // get the time in seconds
        float t = glwtGetNanoTime()*1.e-9f;
        
        // update events
        glwtEventHandle(0);
        
        // clear first
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        
        // use the shader program
        glUseProgram(shader_program);
        
        // calculate ViewProjection matrix
        glm::mat4 Projection = glm::perspective(90.0f, 4.0f / 3.0f, 0.1f, 100.f);
        
        // translate the world/view position
        glm::mat4 View = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, -5.0f));
        
        // make the camera rotate around the origin
        View = glm::rotate(View, 90.0f*t, glm::vec3(1.0f, 1.0f, 1.0f)); 
        
        glm::mat4 ViewProjection = Projection*View;
        
        // set the uniform
        glUniformMatrix4fv(ViewProjection_location, 1, GL_FALSE, glm::value_ptr(ViewProjection)); 
        
        // bind the vao
        glBindVertexArray(vao);

        // draw
        // the additional parameter indicates how many instances to render
        glDrawElementsInstanced(GL_TRIANGLES, 6*6, GL_UNSIGNED_INT, 0, 8);
       
        // check for errors
        GLenum error = glGetError();
        if(error != GL_NO_ERROR)
        {
            userdata.running = false;       
        }
        
        // finally swap buffers
        glwtSwapBuffers(window);       
    }
    
    // delete the created objects
        
    glDeleteVertexArrays(1, &vao);
    glDeleteBuffers(1, &vbo);
    glDeleteBuffers(1, &ibo);
    glDeleteBuffers(1, &tbo);
    
    glDetachShader(shader_program, vertex_shader);      
    glDetachShader(shader_program, fragment_shader);
    glDeleteShader(vertex_shader);
    glDeleteShader(fragment_shader);
    glDeleteProgram(shader_program);
    
    glwtWindowDestroy(window);
    glwtQuit();
    return 0;
}