Esempio n. 1
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;
}
Esempio n. 2
0
Shader::Shader(const GLchar* vertexPath, const GLchar* fragmentPath)
{
	string vertexCode;
	string fragmentCode;
	ifstream vShaderFile;
	ifstream fShaderFile;

	vShaderFile.exceptions(ifstream::badbit);
	fShaderFile.exceptions(ifstream::badbit);

	try
	{
		vShaderFile.open(vertexPath);
		fShaderFile.open(fragmentPath);

		stringstream vShaderStream;
		stringstream fShaderStream;

		vShaderStream << vShaderFile.rdbuf();
		fShaderStream << fShaderFile.rdbuf();

		vShaderFile.close();
		fShaderFile.close();

		vertexCode = vShaderStream.str();
		fragmentCode = fShaderStream.str();
	}
	catch (ifstream::failure e)
	{
		cout << "ERROR::SHADER::FILE_NOT_SUCCESFULLY_READ" << endl;
	}
	
	const GLchar* vShaderCode = vertexCode.c_str();
	const GLchar* fShaderCode = fragmentCode.c_str();

	GLuint vertex;
	GLuint fragment;
	GLint success;
	GLchar infoLog[512];

	vertex = glCreateShader(GL_VERTEX_SHADER);
	glShaderSource(vertex, 1, &vShaderCode, NULL);
	glCompileShader(vertex);
	glGetShaderiv(vertex, GL_COMPILE_STATUS, &success);
	if (!success)
	{
		glGetShaderInfoLog(vertex, 512, NULL, infoLog);
		cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << endl;
	}

	fragment = glCreateShader(GL_FRAGMENT_SHADER);
	glShaderSource(fragment, 1, &fShaderCode, NULL);
	glCompileShader(fragment);
	glGetShaderiv(fragment, GL_COMPILE_STATUS, &success);
	if (!success)
	{
		glGetShaderInfoLog(fragment, 512, NULL, infoLog);
		cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << endl;
	}

	m_program = glCreateProgram();
	glAttachShader(m_program, vertex);
	glAttachShader(m_program, fragment);
	glLinkProgram(m_program);
	glGetProgramiv(m_program, GL_LINK_STATUS, &success);
	if (!success)
	{
		glGetProgramInfoLog(m_program, 512, NULL, infoLog);
		cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << endl;
	}

	glDeleteShader(vertex);
	glDeleteShader(fragment);
}
GLuint CompileProgram(const char *vsource, const char *fsource, const char* gsource)
{

	GLuint vertexShader = GLuint(-1);
	GLuint geometryShader = GLuint(-1); 
	GLuint fragmentShader = GLuint(-1); 

	GLuint program = glCreateProgram();

	if (vsource)
	{
		vertexShader = glCreateShader(GL_VERTEX_SHADER);
		glShaderSource(vertexShader, 1, &vsource, 0);
		glCompileShader(vertexShader);
		GlslPrintShaderLog(vertexShader);
		glAttachShader(program, vertexShader);
	}

	if (fsource)
	{
		fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
		glShaderSource(fragmentShader, 1, &fsource, 0);
		glCompileShader(fragmentShader);
		GlslPrintShaderLog(fragmentShader);
		glAttachShader(program, fragmentShader);
	}

	if (gsource)
	{
		geometryShader = glCreateShader(GL_GEOMETRY_SHADER);
		glShaderSource(geometryShader, 1, &gsource, 0);
		glCompileShader(geometryShader);
		GlslPrintShaderLog(geometryShader);

		// hack, force billboard gs mode
		glAttachShader(program, geometryShader);
		glProgramParameteriEXT ( program, GL_GEOMETRY_VERTICES_OUT_EXT, 4 ) ; 
		glProgramParameteriEXT ( program, GL_GEOMETRY_INPUT_TYPE_EXT, GL_POINTS ) ; 
		glProgramParameteriEXT ( program, GL_GEOMETRY_OUTPUT_TYPE_EXT, GL_TRIANGLE_STRIP ) ; 
	}

	glLinkProgram(program);

	// check if program linked
	GLint success = 0;
	glGetProgramiv(program, GL_LINK_STATUS, &success);

	if (!success) {
		char temp[256];
		glGetProgramInfoLog(program, 256, 0, temp);
		printf("Failed to link program:\n%s\n", temp);
		glDeleteProgram(program);
		program = 0;
	}
	else
	{
		printf("Created shader program: %d\n", program);
	}

	return program;
}
Esempio n. 4
0
	void Shader::finalize()
	{
		char text[1000];
		//
		// bind attribute locations
		//
		glBindAttribLocation(m_glProgram, 0, "P");
		glBindAttribLocation(m_glProgram, 1, "N");
		glBindAttribLocation(m_glProgram, 2, "Cd");
		glBindAttribLocation(m_glProgram, 3, "W");
		glBindAttribLocation(m_glProgram, 4, "CMT");
		glBindAttribLocation(m_glProgram, 5, "BW");
		glBindAttribLocation(m_glProgram, 6, "BI");
		glBindAttribLocation(m_glProgram, 7, "UV");

		//
		// program linking --------
		//
		glLinkProgram(m_glProgram);
		glGetInfoLogARB(m_glProgram, 1000, 0, text);
		std::cout << "Shader::finalize: "<< m_shaderIdentifier << "\n" << text << std::endl;


		// extract active attributes info
		int numActiveAttributes = 0;
		m_activeAttributes.clear();
		glGetProgramiv(m_glProgram, GL_ACTIVE_ATTRIBUTES, &numActiveAttributes);
		std::cout << "number of active attributes: " << numActiveAttributes << std::endl;
		for( int i=0;i<numActiveAttributes; ++i )
		{
			char name[1000];
			int length;
			int size;
			unsigned int type;
			glGetActiveAttrib( m_glProgram, i, 1000, &length, &size, &type, name );
			int index = glGetAttribLocation(m_glProgram, name);
			std::cout << "active attribute " << name << " at location " << index << std::endl;
			m_activeAttributes.insert(std::make_pair( std::string(name), index ));
		}

		// extract active uniforms info
		int numActiveUniforms = 0;
		m_activeUniforms.clear();
		glGetProgramiv(m_glProgram, GL_ACTIVE_UNIFORMS, &numActiveUniforms);
		std::cout << "number of active uniforms: " << numActiveUniforms << std::endl;
		for( int i=0;i<numActiveUniforms; ++i )
		{
			char name[1000];
			int length;
			int size;
			unsigned int type;
			glGetActiveUniform( m_glProgram, i, 1000, &length, &size, &type, name );
			int index = glGetUniformLocation(m_glProgram, name);
			std::cout << "active uniform " << name << " at location " << index << std::endl;

			// index==-1 means uniform is a built in uniform and we dont touch it
			if( index != -1 )
			{

				// f*****g ati laptop cards puts an [i] at the end of array uniforms. have
				// to remove that to remain compatible with the other shit
				int l = (int)strlen( name );
				if( (name[l-3] == '[') && (name[l-2] == '0') && (name[l-1] == ']') )
					name[l-3] = '\0';

				m_activeUniforms.insert( std::make_pair( std::string(name), index) );
			}
		}

		m_isOk = true;
	}
Esempio n. 5
0
int main()
{
	//Initilization of GLFW
	if (!glfwInit())
	{
		return -1;
	}

	//create a windowed mode winow and it's OpenGL context
	GLFWwindow* window;
	window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);

	if (!window)
	{
		glfwTerminate();
		return -1;
	}

	//make the window's context current
	glfwMakeContextCurrent(window);

	//.............................................................................
	//START GLEW BRUH
	if (glewInit() != GLEW_OK)
	{
		// OpenGL didn't start-up! shutdown GLFW and return an error code bruh
		glfwTerminate();
		return -1;
	}
	//..............................................................................
	//looooppppooop unitl user closes windooe

	// GENERATE BUFFERS
	GLuint vao;
	glGenVertexArrays(1, &vao);
	//Start using by bindiing;sehti
	glBindVertexArray(vao);

	GLuint vbo;
	glGenBuffers(1, &vbo); // Generate 1 buffer
	glBindBuffer(GL_ARRAY_BUFFER, vbo);
	glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

	

	GLuint ebo;
	glGenBuffers(1, &ebo);

	GLuint elements[] =
	{
		0, 1, 2,
		2, 3, 0
	};
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elements), elements, GL_STATIC_DRAW);

	// GENERATE SHADERS
//VERTEX
	GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
	glShaderSource(vertexShader, 1, &vertexSource, NULL);
	glCompileShader(vertexShader);
	//TEST
	GLint status;
	glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &status);

	if (status == GL_TRUE)
	{
		printf("Vertex shader compiled successfully bruh\n");
		printf("I furted\n");
	}
	else if (status == GL_FALSE)
	{
		printf("Vertex shader error.\n");
	}
	char buffer[512];
	glGetShaderInfoLog(vertexShader, 512, NULL, buffer);

	printf(buffer);
//-------------------------------------------------------------
	//FRAGMENT
	GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
	glShaderSource(fragmentShader, 1, &fragmentSource, NULL);
	glCompileShader(fragmentShader);
	//TEST(SHIT)
	GLint SHIT;
	glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &SHIT);

	if (SHIT == GL_TRUE)
	{
		printf("Shit's working fragment shader \n");
	}
	else if (SHIT == GL_FALSE)
	{
		printf("SHIT AINT REAL BRUH\n");

	}

	// SHADER PROGRAM
	GLuint shaderProgram = glCreateProgram();
	glAttachShader(shaderProgram, vertexShader);
	glAttachShader(shaderProgram, fragmentShader);
	//glBindFragDataLocation(shaderProgram, 0, "outColor");
	//Linksshit
	glLinkProgram(shaderProgram);
	//start using shit
	glUseProgram(shaderProgram);

	GLint statusProgram;
	glGetProgramiv(shaderProgram, GL_LINK_STATUS, &statusProgram);
	if (statusProgram == GL_FALSE)
	{
		GLint infoLogLength;
		glGetProgramiv(shaderProgram, GL_INFO_LOG_LENGTH, &infoLogLength);

		GLchar *strInfoLog = new GLchar[infoLogLength + 1];
		glGetProgramInfoLog(shaderProgram, infoLogLength, NULL, strInfoLog);

		fprintf(stderr, "Linker failure: %s\n", strInfoLog);
		delete[] strInfoLog;
	}
//=================================================================

	// LOAD TEXTURE
	GLuint textures[2];
	glGenTextures(2, textures);

	glActiveTexture(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_2D, textures[0]);
	int width, height;
	unsigned char* image =
		SOIL_load_image("Sonic.png", &width, &height, 0, SOIL_LOAD_RGB);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
		SOIL_free_image_data(image);
	glUniform1i(glGetUniformLocation(shaderProgram, "texKitten"), 0);

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

	glActiveTexture(GL_TEXTURE1);
	glBindTexture(GL_TEXTURE_2D, textures[1]);
		image = SOIL_load_image("sample2.png", &width, &height, 0, SOIL_LOAD_RGB);
		glTexImage2D(GL_TEXTURE_2D, 0 , GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
		SOIL_free_image_data(image);
	glUniform1i(glGetUniformLocation(shaderProgram, "texPuppy"), 1);


	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

	//Retrieving Postion
	GLint posAttrib = glGetAttribLocation(shaderProgram, "position");
	GLint texAttrib = glGetAttribLocation(shaderProgram, "texcoord");
	GLint colAttrib = glGetAttribLocation(shaderProgram, "color");
	
	
	glEnableVertexAttribArray(posAttrib);
	glEnableVertexAttribArray(texAttrib);
	glEnableVertexAttribArray(colAttrib);

	
	glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, 7 * sizeof(float), 0);
	glVertexAttribPointer(texAttrib, 2, GL_FLOAT, GL_FALSE, 7 * sizeof(float), (void*)(5 * sizeof(float)));
	glVertexAttribPointer(colAttrib, 3, GL_FLOAT, GL_FALSE, 7 * sizeof(float), (void*)(2 * sizeof(float)));	



	//---------------------------------------------------------------------------------------------------------
	//3D tranforms stuffs
	GLint uniTrans = glGetUniformLocation(shaderProgram, "trans");

	//glm::mat4 view = glm::lookAt
	//	(
	//	glm::vec3(1.2f, 1.2f, 1.2f),
	//	glm::vec3(0.0f, 0.0f, 0.0f),
	//	glm::vec3(0.0f, 0.0f, 1.0f)
	//	);
	//GLint uniView = glGetUniformLocation(shaderProgram, "view");
	//glUniformMatrix4fv(uniView, 1, GL_FALSE, glm::value_ptr(view));

	//glm::mat4 proj = glm::perspective(45.0f, 800.0f / 600.0f, 1.0f, 10.0f);
	//GLint uniProj = glGetUniformLocation(shaderProgram, "proj");
	//glUniformMatrix4fv(uniProj, 1, GL_FALSE, glm::value_ptr(proj));

	
	glfwSetTime(0);
	float time = 0;


	while (!glfwWindowShouldClose(window))
	{
		time = glfwGetTime();
		if (time > 1.0f / 10.0f)
		{
			time -= 1.0f / 10.0f;

			// background color
			glClearColor(0.5f, 0.3f, 0.6f, 0.0f);
			glClear(GL_COLOR_BUFFER_BIT);

			// Calculate transformation

			glm::mat4 trans;
			trans = glm::rotate(
				trans,
				(float)clock() / (float)CLOCKS_PER_SEC * glm::radians(0.0f), //Spin and rate
				glm::vec3(0.0f, 0.0f, 1.0f)
				);

			glUniformMatrix4fv(uniTrans, 1, GL_FALSE, glm::value_ptr(trans));

			vertices[5] += 0.1f;
			vertices[12] += 0.1f;
			vertices[19] += 0.1f;
			vertices[26] += 0.1f;

			if (vertices[5] == 1)
			{
				vertices[5] = 0.0f;
				vertices[12] = 0.1f;
				vertices[19] = 0.1f;
				vertices[26] = 0.0f;
			}


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

			//glDrawArrays(GL_TRIANGLES, 0, 6);
			glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);

			//glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_INT, 0);

			//swap front and back buffers
			glfwSwapBuffers(window);
		}
		//poll for and process events
		glfwPollEvents();
	}

	glfwTerminate();
	return 0;

}
Esempio n. 6
0
	PipelineProgram::PipelineProgram(
		const char * inputVertexShader,
		const char * inputTesselationControlShader,
		const char * inputTesselationEvaluationShader,
		const char * inputGeometryShader,
		const char * inputFragmentShader) {
		
		GLint InfoLogLength = 0;
		
		// Create program //
		this->ID = glCreateProgram();
		if (!glIsProgram(this->ID)) {
			throw Exception(DSGL_CANNOT_CREATE_PROGRAM, "DSGL: Cannot create program");
		}	

		// Create shaders //
		this->vertex = std::make_shared<Shader>(inputVertexShader, GL_VERTEX_SHADER, DSGL_READ_FROM_FILE);
		this->tesselationControl = std::make_shared<Shader>(inputTesselationControlShader, GL_TESS_CONTROL_SHADER, DSGL_READ_FROM_FILE);
		this->tesselationEvaluation = std::make_shared<Shader>(inputTesselationEvaluationShader, GL_TESS_EVALUATION_SHADER, DSGL_READ_FROM_FILE);
		this->geometry = std::make_shared<Shader>(inputGeometryShader, GL_GEOMETRY_SHADER, DSGL_READ_FROM_FILE);
		this->fragment = std::make_shared<Shader>(inputFragmentShader, GL_FRAGMENT_SHADER, DSGL_READ_FROM_FILE);

		// Link and compile //

		if (glIsShader(this->vertex->ID)) {
			glAttachShader(this->ID, this->vertex->ID);
		}

		if (glIsShader(this->tesselationControl->ID)) {
			glAttachShader(this->ID, this->tesselationControl->ID);
		}
		
		if (glIsShader(this->tesselationEvaluation->ID)) {
			glAttachShader(this->ID, this->tesselationEvaluation->ID);
		}
		
		if (glIsShader(this->geometry->ID)) {
			glAttachShader(this->ID, this->geometry->ID);
		}
		
		if (glIsShader(this->fragment->ID)) {
			glAttachShader(this->ID, this->fragment->ID);
		}
		
		glLinkProgram(this->ID);
		
		// Clean shaders //
		Clean(DSGL_CLEAN_SHADERS_ONLY);

		glGetProgramiv(this->ID, GL_LINK_STATUS, &this->Result);

		if (!Result) {
			glGetProgramiv(this->ID, GL_INFO_LOG_LENGTH, &InfoLogLength);
			this->programErrorMessages = new char[DSGL_SHADER_ERROR_LENGTH]() ;
			glGetProgramInfoLog(this->ID, GL_INFO_LOG_LENGTH, NULL, &this->programErrorMessages[0]);
			std::cout << this->programErrorMessages << "\n";
			delete[] this->programErrorMessages;
			Clean(DSGL_CLEAN_ALL);
			throw DSGL_ERROR_AT_SHDR_COMPILE_TIME;
		}
	}	
Esempio n. 7
0
    // Constructor generates the shader on the fly
    Shader(const GLchar* vertexPath, const GLchar* fragmentPath) {

        // 1. Retrieve the vertex/fragment source code from filePath
        std::string vertexCode;
        std::string fragmentCode;
        std::ifstream vShaderFile;
        std::ifstream fShaderFile;

        // ensures ifstream objects can throw exceptions:
        vShaderFile.exceptions (std::ifstream::failbit | std::ifstream::badbit);
        fShaderFile.exceptions (std::ifstream::failbit | std::ifstream::badbit);

        try {
            // Open files
            vShaderFile.open(vertexPath);
            fShaderFile.open(fragmentPath);

            // Read file's buffer contents into streams
            std::stringstream vShaderStream, fShaderStream;
            vShaderStream << vShaderFile.rdbuf();
            fShaderStream << fShaderFile.rdbuf();

            // close file handlers
            vShaderFile.close();
            fShaderFile.close();

            // Convert stream into string
            vertexCode = vShaderStream.str();
            fragmentCode = fShaderStream.str();

        } catch (std::ifstream::failure e) {
            std::cout << "ERROR::SHADER::FILE_NOT_SUCCESFULLY_READ" << std::endl;
        }

        const GLchar* vShaderCode = vertexCode.c_str();
        const GLchar * fShaderCode = fragmentCode.c_str();

        // 2. Compile shaders
        GLuint vertex, fragment;
        GLint success;
        GLchar infoLog[512];

        // Vertex Shader
        vertex = glCreateShader(GL_VERTEX_SHADER);
        glShaderSource(vertex, 1, &vShaderCode, NULL);
        glCompileShader(vertex);

        // Print compile errors if any
        glGetShaderiv(vertex, GL_COMPILE_STATUS, &success);
        if (!success) {
            glGetShaderInfoLog(vertex, 512, NULL, infoLog);
            std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;
        }
        // Fragment Shader
        fragment = glCreateShader(GL_FRAGMENT_SHADER);
        glShaderSource(fragment, 1, &fShaderCode, NULL);
        glCompileShader(fragment);

        // Print compile errors if any
        glGetShaderiv(fragment, GL_COMPILE_STATUS, &success);
        if (!success) {
            glGetShaderInfoLog(fragment, 512, NULL, infoLog);
            std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::endl;
        }

        // Shader Program
        this->Program = glCreateProgram();
        glAttachShader(this->Program, vertex);
        glAttachShader(this->Program, fragment);
        glLinkProgram(this->Program);

        // Print linking errors if any
        glGetProgramiv(this->Program, GL_LINK_STATUS, &success);
        if (!success) {
            glGetProgramInfoLog(this->Program, 512, NULL, infoLog);
            std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << std::endl;
        }

        // Delete the shaders as they're linked into our program now and no longer necessery
        glDeleteShader(vertex);
        glDeleteShader(fragment);
    }
Esempio n. 8
0
    virtual void startup()
    {
        static const char * vs_source[] =
        {
            "#version 430 core                                                      \n"
            "                                                                  \n"
            "void main(void)                                                   \n"
            "{                                                                 \n"
            "    const vec4 vertices[] = vec4[](vec4( 0.8, -0.8, 0.5, 1.0),    \n"
            "                                   vec4(-0.8, -0.8, 0.5, 1.0),    \n"
            "                                   vec4( 0.8,  0.8, 0.5, 1.0),    \n"
            "                                   vec4(-0.8,  0.8, 0.5, 1.0));   \n"
            "                                                                  \n"
            "    gl_Position = vertices[gl_VertexID];                          \n"
            "}                                                                 \n"
        };

        static const char * tcs_source_triangles[] =
        {
            "#version 430 core                                                                      \n"
            "                                                                                  \n"
            "layout (vertices = 3) out;                                                        \n"
            "                                                                                  \n"
            "uniform float tess_level = 2.7;                                                   \n"
            "                                                                                  \n"
            "void main(void)                                                                   \n"
            "{                                                                                 \n"
            "    if (gl_InvocationID == 0)                                                     \n"
            "    {                                                                             \n"
            "        gl_TessLevelInner[0] = tess_level;                                        \n"
            "        gl_TessLevelOuter[0] = tess_level;                                        \n"
            "        gl_TessLevelOuter[1] = tess_level;                                        \n"
            "        gl_TessLevelOuter[2] = tess_level;                                        \n"
            "    }                                                                             \n"
            "    gl_out[gl_InvocationID].gl_Position = gl_in[gl_InvocationID].gl_Position;     \n"
            "}                                                                                 \n"
        };

        static const char * tes_source_equal[] =
        {
            "#version 430 core                                                                      \n"
            "                                                                                  \n"
            "layout (triangles) in;                                                            \n"
            "                                                                                  \n"
            "void main(void)                                                                   \n"
            "{                                                                                 \n"
            "    gl_Position = (gl_TessCoord.x * gl_in[0].gl_Position) +                       \n"
            "                  (gl_TessCoord.y * gl_in[1].gl_Position) +                       \n"
            "                  (gl_TessCoord.z * gl_in[2].gl_Position);                        \n"
            "}                                                                                 \n"
        };

        static const char * tes_source_fract_even[] =
        {
            "#version 430 core                                                                      \n"
            "                                                                                  \n"
            "layout (triangles, fractional_even_spacing) in;                                   \n"
            "                                                                                  \n"
            "void main(void)                                                                   \n"
            "{                                                                                 \n"
            "    gl_Position = (gl_TessCoord.x * gl_in[0].gl_Position) +                       \n"
            "                  (gl_TessCoord.y * gl_in[1].gl_Position) +                       \n"
            "                  (gl_TessCoord.z * gl_in[2].gl_Position);                        \n"
            "}                                                                                 \n"
        };

        static const char * tes_source_fract_odd[] =
        {
            "#version 430 core                                                                      \n"
            "                                                                                  \n"
            "layout (triangles, fractional_odd_spacing) in;                                    \n"
            "                                                                                  \n"
            "void main(void)                                                                   \n"
            "{                                                                                 \n"
            "    gl_Position = (gl_TessCoord.x * gl_in[0].gl_Position) +                       \n"
            "                  (gl_TessCoord.y * gl_in[1].gl_Position) +                       \n"
            "                  (gl_TessCoord.z * gl_in[2].gl_Position);                        \n"
            "}                                                                                 \n"
        };

        static const char * fs_source[] =
        {
            "#version 430 core                                                       \n"
            "                                                                   \n"
            "out vec4 color;                                                    \n"
            "                                                                   \n"
            "void main(void)                                                    \n"
            "{                                                                  \n"
            "    color = vec4(1.0);                                             \n"
            "}                                                                  \n"
        };

        int i;

        static const char * const * vs_sources[] =
        {
            vs_source, vs_source, vs_source
        };

        static const char * const * tcs_sources[] =
        {
            tcs_source_triangles, tcs_source_triangles, tcs_source_triangles
        };

        static const char * const * tes_sources[] =
        {
            tes_source_equal, tes_source_fract_even, tes_source_fract_odd
        };

        static const char * const * fs_sources[] =
        {
            fs_source, fs_source, fs_source
        };

        for (i = 0; i < 3; i++)
        {
            program[i] = glCreateProgram();
            GLuint vs = glCreateShader(GL_VERTEX_SHADER);
            glShaderSource(vs, 1, vs_sources[i], NULL);
            glCompileShader(vs);

            GLuint tcs = glCreateShader(GL_TESS_CONTROL_SHADER);
            glShaderSource(tcs, 1, tcs_sources[i], NULL);
            glCompileShader(tcs);

            GLuint tes = glCreateShader(GL_TESS_EVALUATION_SHADER);
            glShaderSource(tes, 1, tes_sources[i], NULL);
            glCompileShader(tes);

            GLuint fs = glCreateShader(GL_FRAGMENT_SHADER);
            glShaderSource(fs, 1, fs_sources[i], NULL);
            glCompileShader(fs);

            glAttachShader(program[i], vs);
            glAttachShader(program[i], tcs);
            glAttachShader(program[i], tes);
            glAttachShader(program[i], fs);
            glLinkProgram(program[i]);

            glDeleteShader(vs);
            glDeleteShader(tcs);
            glDeleteShader(tes);
            glDeleteShader(fs);
        }

        glGenVertexArrays(1, &vao);
        glBindVertexArray(vao);

        glPatchParameteri(GL_PATCH_VERTICES, 4);
        glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
    }
Esempio n. 9
0
static GLboolean
render_and_check_textures(GLenum internal_format)
{
	GLuint rgba_fb;
	GLuint other_fb;
	float rgba_image[4 * 64 * 64];
	float other_image[4 * 64 * 64];
	GLboolean has_green;
	GLuint vs;
	GLuint fs;
	GLint scale_loc;
	GLint bias_loc;
	float scale;
	float bias;

	piglit_require_extension("GL_EXT_framebuffer_object");
	piglit_require_extension("GL_ARB_texture_rg");

	has_green = GL_FALSE;
	scale = 1.0;
	bias = 0.0;
	switch (internal_format) {
	case GL_RG:
	case GL_RG8:
	case GL_RG16:
		has_green = GL_TRUE;
		/* FALLTHROUGH */
	case GL_RED:
	case GL_R8:
	case GL_R16:
		break;

	case GL_RG16F:
		has_green = GL_TRUE;
		/* FALLTHROUGH */
	case GL_R16F:
		piglit_require_extension("GL_ARB_half_float_pixel");
		/* FALLTHROUGH */
	case GL_RG32F:
		has_green = GL_TRUE;
		/* FALLTHROUGH */
	case GL_R32F:
		scale = 511.0;
		piglit_require_extension("GL_ARB_texture_float");
		break;

	case GL_RG_INTEGER:
	case GL_RG8I:
	case GL_RG16I:
	case GL_RG32I:
		has_green = GL_TRUE;
		/* FALLTHROUGH */
	case GL_R8I:
	case GL_R16I:
	case GL_R32I:
		bias = -100.0;
		scale = 511.0;
		piglit_require_extension("GL_EXT_texture_integer");
		break;

	case GL_RG8UI:
	case GL_RG16UI:
	case GL_RG32UI:
		has_green = GL_TRUE;
		/* FALLTHROUGH */
	case GL_R16UI:
	case GL_R32UI:
		scale = 511.0;
		piglit_require_extension("GL_EXT_texture_integer");
		break;

	case GL_RG_SNORM:
	case GL_RG8_SNORM:
	case GL_RG16_SNORM:
		has_green = GL_TRUE;
		/* FALLTHROUGH */
	case GL_RED_SNORM:
	case GL_R8_SNORM:
	case GL_R16_SNORM:
		scale = 0.5;
		bias = -0.5;
		piglit_require_extension("GL_EXT_texture_snorm");
		break;
	default:
		fprintf(stderr, "invalid format 0x%04x\n", internal_format);
		piglit_report_result(PIGLIT_FAIL);
		break;
	}

	glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE,
			      2 * sizeof(GLfloat), positions);
	glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE,
			      4 * sizeof(GLfloat), colors);

	glEnableVertexAttribArray(0);
	glEnableVertexAttribArray(1);

	vs = piglit_compile_shader_text(GL_VERTEX_SHADER, vert_code);
	fs = piglit_compile_shader_text(GL_FRAGMENT_SHADER, frag_code);
	fbo_program = piglit_link_simple_program(vs, fs);

	glBindAttribLocation(fbo_program, 0, "position");
	glBindAttribLocation(fbo_program, 1, "color");
	glLinkProgram(fbo_program);
	if (!piglit_link_check_status(fbo_program))
		piglit_report_result(PIGLIT_FAIL);

	scale_loc = glGetUniformLocation(fbo_program, "scale");
	if (scale_loc < 0) {
		fprintf(stderr,
			"couldn't get uniform location for \"scale\"\n");
		piglit_report_result(PIGLIT_FAIL);
	}

	bias_loc = glGetUniformLocation(fbo_program, "bias");
	if (bias_loc < 0) {
		fprintf(stderr,
			"couldn't get uniform location for \"bias\"\n");
		piglit_report_result(PIGLIT_FAIL);
	}

	glUseProgram(fbo_program);
	glUniform1f(scale_loc, scale);
	glUniform1f(bias_loc, bias);

	/* Draw the reference image to the RGBA texture.
	 */
	rgba_fb = create_fbo(64, 64, GL_RGBA);
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, rgba_fb);
	glViewport(0, 0, 64, 64);
	glDrawArrays(GL_TRIANGLE_FAN, 0, 4);

	glGetFramebufferAttachmentParameterivEXT(GL_FRAMEBUFFER_EXT,
						 GL_COLOR_ATTACHMENT0_EXT,
						 GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_EXT,
						 (GLint *) &rgba_tex);
	glBindTexture(GL_TEXTURE_2D, rgba_tex);
	glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_FLOAT, rgba_image);


	/* Draw the comparison image to the other texture.
	 */
	other_fb = create_fbo(64, 64, internal_format);
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, other_fb);
	glViewport(0, 0, 64, 64);
	glDrawArrays(GL_TRIANGLE_FAN, 0, 4);

	glGetFramebufferAttachmentParameterivEXT(GL_FRAMEBUFFER_EXT,
						 GL_COLOR_ATTACHMENT0_EXT,
						 GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_EXT,
						 (GLint *) &other_tex);
	glBindTexture(GL_TEXTURE_2D, other_tex);
	glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_FLOAT, other_image);

	glUseProgram(0);
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, piglit_winsys_fbo);
	glViewport(0, 0, piglit_width, piglit_height);

	return compare_texture(rgba_image, other_image,
			       internal_format, GL_RGBA,
			       64 * 64, has_green);
}
Esempio n. 10
0
int main(int argc, char *argv[])
{
    SDL_Surface *screen;
    if ( SDL_Init(SDL_INIT_VIDEO) != 0 ) {
        printf("Unable to initialize SDL: %s\n", SDL_GetError());
        return 1;
    }

    SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );
    screen = SDL_SetVideoMode( 640, 480, 24, SDL_OPENGL );
    if ( !screen ) {
        printf("Unable to set video mode: %s\n", SDL_GetError());
        return 1;
    }
    
    glClearColor( 0, 0, 0, 0 );
    glClear( GL_COLOR_BUFFER_BIT );

    // Fog

    glEnable(GL_FOG);
    glFogf(GL_FOG_START, 100);
    glFogf(GL_FOG_END, 2000);
    glFogi(GL_FOG_MODE, GL_LINEAR);
    GLfloat fogcolor[4] = { 0.9, 0.1, 0.35, 0 };
    glFogfv(GL_FOG_COLOR, fogcolor);

    // Create a texture

    GLuint texture;
    glGenTextures( 1, &texture );
    glBindTexture( GL_TEXTURE_2D, texture );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
    GLubyte textureData[16*16*4];
    for (int x = 0; x < 16; x++) {
      for (int y = 0; y < 16; y++) {
        *((int*)&textureData[(x*16 + y) * 4]) = x*16 + ((y*16) << 8);
      }
    }
    glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, 16, 16, 0, 
                  GL_RGBA, GL_UNSIGNED_BYTE, textureData );

    // Create a second texture

    GLuint texture2;
    glGenTextures( 1, &texture2 );
    glBindTexture( GL_TEXTURE_2D, texture2 );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
    GLubyte texture2Data[] = { 0xff,    0,    0, 0xff,
                                  0, 0xff,    0, 0xaa,
                                  0,    0, 0xff, 0x55,
                               0x80, 0x90, 0x70,    0 };
    glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, 2, 2, 0,
                  GL_RGBA, GL_UNSIGNED_BYTE, texture2Data );
    
    // BEGIN

#if USE_GLEW
    glewInit();
#endif

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    // original: glFrustum(-0.6435469817188064, 0.6435469817188064 ,-0.48266022190470925, 0.48266022190470925 ,0.5400000214576721, 2048);
    glFrustum(-0.6435469817188064, 0.1435469817188064 ,-0.48266022190470925, 0.88266022190470925 ,0.5400000214576721, 2048);
    glRotatef(-30, 1, 1, 1);
    //GLfloat pm[] = { 1.372136116027832, 0, 0, 0, 0, 0.7910231351852417, 0, 0, -0.6352481842041016, 0.29297152161598206, -1.0005275011062622, -1, 0, 0, -1.080284833908081, 0 };
    //glLoadMatrixf(pm);

    glMatrixMode(GL_MODELVIEW);
    GLfloat matrixData[] = { -1, 0, 0, 0,
                              0, 0,-1, 0,
                              0, 1, 0, 0,
                              0, 0, 0, 1 };
    glLoadMatrixf(matrixData);
    //glTranslated(-512,-512,-527); // XXX this should be uncommented, but if it is then nothing is shown

    glEnable(GL_CULL_FACE);
    glEnable(GL_DEPTH_TEST);

    glClear(GL_DEPTH_BUFFER_BIT);

    glEnableClientState(GL_NORMAL_ARRAY);
    glEnableClientState(GL_COLOR_ARRAY);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);

    glActiveTexture(GL_TEXTURE0);

    glEnableClientState(GL_VERTEX_ARRAY);

    GLuint arrayBuffer, elementBuffer;
    glGenBuffers(1, &arrayBuffer);
    glGenBuffers(1, &elementBuffer);

    GLubyte arrayData[] = {
/*
[0, 0,   0, 67] ==>  128 float
[0, 0, 128, 67] ==>  256 float
[0, 0,   0, 68] ==>  512 float
[0, 0, 128, 68] ==> 1024 float

[vertex x        ] [vertex y         ] [vertex z         ] [nr]                [texture u        ] [texture v        ] [lm u   ] [lm v   ] [color r,g,b,a    ] */
  0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,  68,  11,   10,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128, //  0
  0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,  68,  23,   20,   0,   0,   0,   0,   0,  67,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128, //  1
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,  68,  35,   30,   0,   0,   0,   0,   0,  67,   0,   0,   0,  67,   0,   0,   0,   0, 128, 128, 128, 128, //  2
  0,   0,   0,   0,   0,   0,   0,  68,   0,   0,   0,  68,  47,   40,   0,   0,   0,   0,   0,   0,   0,   0,   0,  67,   0,   0,   0,   0, 128, 128, 128, 128, //  3
  0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,  68,  51,   50,   0,   0,   0,   0,   0,  67,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128, //  4
  0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,  68,  64,   60,   0,   0,   0,   0, 128,  67,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128, //  5
  0,   0, 128,  68,   0,   0,   0,  68,   0,   0,   0,  68,  70,   70,   0,   0,   0,   0, 128,  67,   0,   0,   0,  67,   0,   0,   0,   0, 128, 128, 128, 128, //  6
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,  68,  89,   80,   0,   0,   0,   0,   0,  67,   0,   0,   0,  67,   0,   0,   0,   0, 128, 128, 128, 128, //  7
  0,   0,   0,   0,   0,   0,   0,  68,   0,   0,   0,  68,  94,   90,   0,   0,   0,   0,   0,   0,   0,   0,   0,  67,   0,   0,   0,   0, 128, 128, 128, 128, //  8
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,  68,  20,   10,   0,   0,   0,   0,   0,  67,   0,   0,   0,  67,   0,   0,   0,   0, 128, 128, 128, 128, //  9
  0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,  68,  31,   20,   0,   0,   0,   0,   0,  67,   0,   0, 128,  67,   0,   0,   0,   0, 128, 128, 128, 128, // 10
  0,   0,   0,   0,   0,   0, 128,  68,   0,   0,   0,  68,  42,   30,   0,   0,   0,   0,   0,   0,   0,   0, 128,  67,   0,   0,   0,   0, 128, 128, 128, 128, // 11
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,  68,  53,   40,   0,   0,   0,   0,   0,  67,   0,   0,   0,  67,   0,   0,   0,   0, 128, 128, 128, 128, // 12
  0,   0, 128,  68,   0,   0,   0,  68,   0,   0,   0,  68,  64,   50,   0,   0,   0,   0, 128,  67,   0,   0,   0,  67,   0,   0,   0,   0, 128, 128, 128, 128, // 13
  0,   0, 128,  68,   0,   0, 128,  68,   0,   0,   0,  68,  75,   60,   0,   0,   0,   0, 128,  67,   0,   0, 128,  67,   0,   0,   0,   0, 128, 128, 128, 128, // 14
  0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,  68,  86,   70,   0,   0,   0,   0,   0,  67,   0,   0, 128,  67,   0,   0,   0,   0, 128, 128, 128, 128, // 15

  0,   0,   0,  68,   0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,   0,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,   0,   0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,   0,   0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,   0,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0, 128,  68,   0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0, 128,  68,   0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0, 128,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,   0,   0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,   0,   0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,   0,   0,   0, 128,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0, 128,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0, 128,  68,   0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0, 128,  68,   0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0, 128,  68,   0,   0, 128,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128
    };
    assert(sizeof(arrayData) == 1408);
    glBindBuffer(GL_ARRAY_BUFFER, arrayBuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(arrayData), arrayData, GL_STATIC_DRAW);
    glBindBuffer(GL_ARRAY_BUFFER, 0);

    GLushort elementData[] = { 1, 2, 0, 2, 3, 0, 5, 6, 4, 6, 7, 4, 9, 10, 8, 10, 11, 8, 13, 14, 12, 14, 15, 12 };
    assert(sizeof(elementData) == 48);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementBuffer);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elementData), elementData, GL_STATIC_DRAW);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

    glBindBuffer(GL_ARRAY_BUFFER, arrayBuffer);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementBuffer);

    // sauer vertex data is apparently 0-12: V3F, 12: N1B, 16-24: T2F, 24-28: T2S, 28-32: C4B
    glVertexPointer(3, GL_FLOAT, 32, (void*)0); // all these apply to the ARRAY_BUFFER that is bound
    glTexCoordPointer(2, GL_FLOAT, 32, (void*)16);
    glClientActiveTexture(GL_TEXTURE1); // XXX seems to be ignored in native build
    glTexCoordPointer(2, GL_SHORT, 32, (void*)24);
    glClientActiveTexture(GL_TEXTURE0); // likely not needed, it is a cleanup
    glNormalPointer(GL_BYTE, 32, (void*)12);
    glColorPointer(4, GL_UNSIGNED_BYTE, 32, (void*)28);

    glBindTexture(GL_TEXTURE_2D, texture); // diffuse?
    glActiveTexture(GL_TEXTURE0);
    glActiveTexture(GL_TEXTURE1);
    glBindTexture(GL_TEXTURE_2D, texture2); // lightmap?
    glActiveTexture(GL_TEXTURE0);

    GLint ok;

    const char *vertexShader = "uniform vec4 texgenscroll;\n"
                               "void main(void)\n"
                               "{\n"
                               "    gl_Position = ftransform();\n"
                               "    gl_TexCoord[0].xy = gl_MultiTexCoord0.xy/10000.0 + (0.001*texgenscroll.xy) + gl_Normal.xy;\n" // added /100 here
                               "    gl_TexCoord[1].xy = gl_MultiTexCoord1.xy/100.0 * 3.051851e-05;\n"
                               "    gl_FogFragCoord = gl_Position.z;\n"
                               "}\n";
    const char *fragmentShader = "uniform vec4 colorparams;\n"
                                 "uniform sampler2D diffusemap, lightmap;\n"
                                 "void main(void)\n"
                                 "{\n"
                                 "    vec4 diffuse = texture2D(diffusemap, gl_TexCoord[0].xy);\n"
                                 "    vec4 lm = texture2D(lightmap, gl_TexCoord[1].xy);\n"
                                 "    diffuse *= colorparams;\n"
                                 "    vec4 color = diffuse * lm;\n"
                                 "    gl_FragColor.rgb = mix((gl_Fog.color).rgb, color.rgb, clamp((gl_Fog.end - gl_FogFragCoord) * gl_Fog.scale, 0.0, 1.0));\n"
                                 //"    gl_FragColor.rgb = 0.0001 * color.rgb + ((gl_Fog.color).rgb * (1.0-clamp((gl_FogFragCoord)* 1.0/1000.0, 0.0, 1.0)));\n"
                                 "}\n";

    GLuint vs = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vs, 1, &vertexShader, NULL);
    glCompileShader(vs);
    glGetShaderiv(vs, GL_COMPILE_STATUS, &ok);
    assert(ok);

    GLuint fs = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fs, 1, &fragmentShader, NULL);
    glCompileShader(fs);
    glGetShaderiv(fs, GL_COMPILE_STATUS, &ok);
    assert(ok);

    GLuint program = glCreateProgram();

    glAttachShader(program, vs);
    glAttachShader(program, fs);
    glLinkProgram(program);
    glGetProgramiv(program, GL_LINK_STATUS, &ok);
    assert(ok);

    glUseProgram(program);

    GLint lightmapLocation = glGetUniformLocation(program, "lightmap");
    assert(lightmapLocation >= 0);
    glUniform1i(lightmapLocation, 1); // sampler2D? Is it the texture unit?

    GLint diffusemapLocation = glGetUniformLocation(program, "diffusemap");
    assert(diffusemapLocation >= 0);
    glUniform1i(diffusemapLocation, 0);

    GLint texgenscrollLocation = glGetUniformLocation(program, "texgenscroll");
    assert(texgenscrollLocation >= 0);

    GLint colorparamsLocation = glGetUniformLocation(program, "colorparams");
    assert(colorparamsLocation >= 0);

    GLfloat texgenscrollData[] = { 0, 0, 0, 0 };
    glUniform4fv(texgenscrollLocation, 1, texgenscrollData);

    GLfloat colorparamsData[] = { 2, 2, 2, 1 };
    glUniform4fv(colorparamsLocation, 1, colorparamsData);

    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (void*)12);
    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (void*) 0);
    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (void*)24);
    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (void*)36);

    // END

    SDL_GL_SwapBuffers();

#if !EMSCRIPTEN
    SDL_Delay(1500);
#endif

    SDL_Quit();
    
    return 0;
}
Esempio n. 11
0
void CMyOGLApp::Init()
{
	// törlési szín legyen kékes
	glClearColor(0.125f, 0.25f, 0.5f, 1.0f);

	glEnable(GL_CULL_FACE); // kapcsoljuk be a hatrafele nezo lapok eldobasat
	glEnable(GL_DEPTH_TEST); // mélységi teszt bekapcsolása (takarás)

	//
	// geometria letrehozasa
	//

	Vertex vert[] =
	{ 
		{glm::vec3(-1, -1, 0), glm::vec3(1, 0, 0)},
		{glm::vec3(-1,  1, 0), glm::vec3(0, 0, 1)},
		{glm::vec3( 1, -1, 0), glm::vec3(0, 1, 0)},
		{glm::vec3( 1,  1, 0), glm::vec3(1, 1, 1)},
	};

	// 1 db VAO foglalasa
	glGenVertexArrays(1, &m_vaoID);
	// a frissen generált VAO beallitasa aktívnak
	glBindVertexArray(m_vaoID);
	
	// hozzunk létre egy új VBO erõforrás nevet
	glGenBuffers(1, &m_vboID); 
	glBindBuffer(GL_ARRAY_BUFFER, m_vboID); // tegyük "aktívvá" a létrehozott VBO-t
	// töltsük fel adatokkal az aktív VBO-t
	glBufferData( GL_ARRAY_BUFFER,	// az aktív VBO-ba töltsünk adatokat
				  sizeof(vert),		// ennyi bájt nagyságban
				  vert,	// errõl a rendszermemóriabeli címrõl olvasva
				  GL_STATIC_DRAW);	// úgy, hogy a VBO-nkba nem tervezünk ezután írni és minden kirajzoláskor felhasnzáljuk a benne lévõ adatokat
	

	// VAO-ban jegyezzük fel, hogy a VBO-ban az elsõ 3 float sizeof(Vertex)-enként lesz az elsõ attribútum (pozíció)
	glEnableVertexAttribArray(0); // ez lesz majd a pozíció
	glVertexAttribPointer(
		(GLuint)0,				// a VB-ben található adatok közül a 0. "indexû" attribútumait állítjuk be
		3,				// komponens szam
		GL_FLOAT,		// adatok tipusa
		GL_FALSE,		// normalizalt legyen-e
		sizeof(Vertex),	// stride (0=egymas utan)
		0				// a 0. indexû attribútum hol kezdõdik a sizeof(Vertex)-nyi területen belül
	); 

	// a második attribútumhoz pedig a VBO-ban sizeof(Vertex) ugrás után sizeof(glm::vec3)-nyit menve újabb 3 float adatot találunk (szín)
	glEnableVertexAttribArray(1); // ez lesz majd a szín
	glVertexAttribPointer(
		(GLuint)1,
		3, 
		GL_FLOAT,
		GL_FALSE,
		sizeof(Vertex),
		(void*)(sizeof(glm::vec3)) );

	glBindVertexArray(0); // feltöltüttük a VAO-t, kapcsoljuk le
	glBindBuffer(GL_ARRAY_BUFFER, 0); // feltöltöttük a VBO-t is, ezt is vegyük le

	//
	// shaderek betöltése
	//
	GLuint vs_ID = loadShader(GL_VERTEX_SHADER,		"myVert.vert");
	GLuint fs_ID = loadShader(GL_FRAGMENT_SHADER,	"myFrag.frag");

	// a shadereket tároló program létrehozása
	m_programID = glCreateProgram();

	// adjuk hozzá a programhoz a shadereket
	glAttachShader(m_programID, vs_ID);
	glAttachShader(m_programID, fs_ID);

	// attributomok osszerendelese a VAO es shader kozt
	glBindAttribLocation( m_programID, 0, "vs_in_pos");
	glBindAttribLocation( m_programID, 1, "vs_in_col");

	// illesszük össze a shadereket (kimenõ-bemenõ változók összerendelése stb.)
	glLinkProgram(m_programID);

	// linkeles ellenorzese
	GLint infoLogLength = 0, result = 0;

	glGetProgramiv(m_programID, GL_LINK_STATUS, &result);
	glGetProgramiv(m_programID, GL_INFO_LOG_LENGTH, &infoLogLength);
	if ( infoLogLength > 1)
	{
		std::vector<char> ProgramErrorMessage( infoLogLength );
		glGetProgramInfoLog(m_programID, infoLogLength, NULL, &ProgramErrorMessage[0]);
		fprintf(stdout, "%s\n", &ProgramErrorMessage[0]);
		
		char* aSzoveg = new char[ProgramErrorMessage.size()];
		memcpy( aSzoveg, &ProgramErrorMessage[0], ProgramErrorMessage.size());

		MessageBoxA(0, aSzoveg, "Sáder Huba panasza", 0);

		delete aSzoveg;
	}

	// mar nincs ezekre szukseg
	glDeleteShader( vs_ID );
	glDeleteShader( fs_ID );

	//
	// egyéb inicializálás
	//

	// vetítési mátrix létrehozása
	m_matProj = glm::perspective( 45.0f, m_client_width/(float)m_client_height, 1.0f, 1000.0f );

	// shader-beli transzformációs mátrixok címének lekérdezése
	m_loc_world = glGetUniformLocation( m_programID, "world");
	m_loc_view  = glGetUniformLocation( m_programID, "view" );
	m_loc_proj  = glGetUniformLocation( m_programID, "proj" );

}
Esempio n. 12
0
GLuint InitShader(const char* vShader, const char* fShader)
{
  Shader shaders[2];
  shaders[0].filename = vShader;
  shaders[0].type = GL_VERTEX_SHADER;
  shaders[1].filename = fShader;
  shaders[1].type = GL_FRAGMENT_SHADER;

  // create the program in the GPU
  GLuint program = glCreateProgram();

  for ( int i = 0; i < 2; ++i )
  {
    Shader& s = shaders[i];

    // read file contents onto ONE LINE, doesn't seem to work
    // if file passed to glShaderSource in multiple lines
    bool read = readShaderSource( s.filename, s.source );
   
    if ( !read )
    {
      std::cerr << "Failed to read " << s.filename << std::endl;
      exit( EXIT_FAILURE );
    }
    
    // First build the shader
    GLuint shader = glCreateShader( s.type );
    
    // Second load the source
    const GLchar* sourceCode = s.source.c_str();
    glShaderSource( shader, 1, const_cast<const GLchar**>(&sourceCode), NULL );
    
    // Third compile the shader
    glCompileShader( shader );

    // Make sure it compiled, other display error message
    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 );
    }

    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;
}
Esempio n. 13
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);
}
Esempio n. 14
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;
}
Esempio n. 15
0
GPUShader *GPU_shader_create_ex(const char *vertexcode,
                                const char *fragcode,
                                const char *geocode,
                                const char *libcode,
                                const char *defines,
                                int input,
                                int output,
                                int number,
                                const int flags)
{
#ifdef WITH_OPENSUBDIV
	/* TODO(sergey): used to add #version 150 to the geometry shader.
	 * Could safely be renamed to "use_geometry_code" since it's very
	 * likely any of geometry code will want to use GLSL 1.5.
	 */
	bool use_opensubdiv = (flags & GPU_SHADER_FLAGS_SPECIAL_OPENSUBDIV) != 0;
#else
	UNUSED_VARS(flags);
	bool use_opensubdiv = false;
#endif
	GLint status;
	GLchar log[5000];
	GLsizei length = 0;
	GPUShader *shader;
	char standard_defines[MAX_DEFINE_LENGTH] = "";
	char standard_extensions[MAX_EXT_DEFINE_LENGTH] = "";

	if (geocode && !GPU_geometry_shader_support())
		return NULL;

	shader = MEM_callocN(sizeof(GPUShader), "GPUShader");

	if (vertexcode)
		shader->vertex = glCreateShader(GL_VERTEX_SHADER);
	if (fragcode)
		shader->fragment = glCreateShader(GL_FRAGMENT_SHADER);
	if (geocode)
		shader->geometry = glCreateShader(GL_GEOMETRY_SHADER_EXT);

	shader->program = glCreateProgram();

	if (!shader->program ||
	    (vertexcode && !shader->vertex) ||
	    (fragcode && !shader->fragment) ||
	    (geocode && !shader->geometry))
	{
		fprintf(stderr, "GPUShader, object creation failed.\n");
		GPU_shader_free(shader);
		return NULL;
	}

	gpu_shader_standard_defines(standard_defines,
	                            use_opensubdiv,
	                            (flags & GPU_SHADER_FLAGS_NEW_SHADING) != 0);
	gpu_shader_standard_extensions(standard_extensions, geocode != NULL);

	if (vertexcode) {
		const char *source[5];
		/* custom limit, may be too small, beware */
		int num_source = 0;

		source[num_source++] = gpu_shader_version();
		source[num_source++] = standard_extensions;
		source[num_source++] = standard_defines;

		if (defines) source[num_source++] = defines;
		source[num_source++] = vertexcode;

		glAttachShader(shader->program, shader->vertex);
		glShaderSource(shader->vertex, num_source, source, NULL);

		glCompileShader(shader->vertex);
		glGetShaderiv(shader->vertex, GL_COMPILE_STATUS, &status);

		if (!status) {
			glGetShaderInfoLog(shader->vertex, sizeof(log), &length, log);
			shader_print_errors("compile", log, source, num_source);

			GPU_shader_free(shader);
			return NULL;
		}
	}

	if (fragcode) {
		const char *source[7];
		int num_source = 0;

		source[num_source++] = gpu_shader_version();
		source[num_source++] = standard_extensions;
		source[num_source++] = standard_defines;

#ifdef WITH_OPENSUBDIV
		/* TODO(sergey): Move to fragment shader source code generation. */
		if (use_opensubdiv) {
			source[num_source++] =
			        "#ifdef USE_OPENSUBDIV\n"
			        "in block {\n"
			        "	VertexData v;\n"
			        "} inpt;\n"
			        "#endif\n";
		}
#endif

		if (defines) source[num_source++] = defines;
		if (libcode) source[num_source++] = libcode;
		source[num_source++] = fragcode;

		glAttachShader(shader->program, shader->fragment);
		glShaderSource(shader->fragment, num_source, source, NULL);

		glCompileShader(shader->fragment);
		glGetShaderiv(shader->fragment, GL_COMPILE_STATUS, &status);

		if (!status) {
			glGetShaderInfoLog(shader->fragment, sizeof(log), &length, log);
			shader_print_errors("compile", log, source, num_source);

			GPU_shader_free(shader);
			return NULL;
		}
	}

	if (geocode) {
		const char *source[6];
		int num_source = 0;

		source[num_source++] = gpu_shader_version();
		source[num_source++] = standard_extensions;
		source[num_source++] = standard_defines;

		if (defines) source[num_source++] = defines;
		source[num_source++] = geocode;

		glAttachShader(shader->program, shader->geometry);
		glShaderSource(shader->geometry, num_source, source, NULL);

		glCompileShader(shader->geometry);
		glGetShaderiv(shader->geometry, GL_COMPILE_STATUS, &status);

		if (!status) {
			glGetShaderInfoLog(shader->geometry, sizeof(log), &length, log);
			shader_print_errors("compile", log, source, num_source);

			GPU_shader_free(shader);
			return NULL;
		}
		
		if (!use_opensubdiv) {
			GPU_shader_geometry_stage_primitive_io(shader, input, output, number);
		}
	}

#ifdef WITH_OPENSUBDIV
	if (use_opensubdiv) {
		glBindAttribLocation(shader->program, 0, "position");
		glBindAttribLocation(shader->program, 1, "normal");
		GPU_shader_geometry_stage_primitive_io(shader,
		                                       GL_LINES_ADJACENCY_EXT,
		                                       GL_TRIANGLE_STRIP,
		                                       4);
	}
#endif

	glLinkProgram(shader->program);
	glGetProgramiv(shader->program, GL_LINK_STATUS, &status);
	if (!status) {
		glGetProgramInfoLog(shader->program, sizeof(log), &length, log);
		/* print attached shaders in pipeline order */
		if (vertexcode) shader_print_errors("linking", log, &vertexcode, 1);
		if (geocode) shader_print_errors("linking", log, &geocode, 1);
		if (libcode) shader_print_errors("linking", log, &libcode, 1);
		if (fragcode) shader_print_errors("linking", log, &fragcode, 1);

		GPU_shader_free(shader);
		return NULL;
	}

#ifdef WITH_OPENSUBDIV
	/* TODO(sergey): Find a better place for this. */
	if (use_opensubdiv && GLEW_VERSION_4_1) {
		glProgramUniform1i(shader->program,
		                   glGetUniformLocation(shader->program, "FVarDataOffsetBuffer"),
		                   30);  /* GL_TEXTURE30 */

		glProgramUniform1i(shader->program,
		                   glGetUniformLocation(shader->program, "FVarDataBuffer"),
		                   31);  /* GL_TEXTURE31 */
	}
#endif

	return shader;
}
Esempio n. 16
0
Obj::Obj(Vertex* vertices, int numverts, GLuint* elements, int numelements, char* vertex_shader_file, char* tessc_shader_file, char* tesse_shader_file, char* geom_shader_file, char* frag_shader_file) {
	this->numelements = numelements;

	use_tess = !(tesse_shader_file == NULL || tessc_shader_file == NULL);

	GLuint vertexshader, tessellationcontrolshader, tessellationevaluationshader, geometryshader, fragmentshader;
	shader_program = glCreateProgram();

	char* vertex_source = filetobuf(vertex_shader_file);
	vertexshader = glCreateShader(GL_VERTEX_SHADER);
	glShaderSource(vertexshader, 1, (const GLchar **) &vertex_source, 0);
	glCompileShader(vertexshader);
	glAttachShader(shader_program, vertexshader);
	
	if(use_tess) {
		char* tessc_source = filetobuf(tessc_shader_file);
		tessellationcontrolshader = glCreateShader(GL_TESS_CONTROL_SHADER);
		glShaderSource(tessellationcontrolshader, 1, (const GLchar **) &tessc_source, 0);
		glCompileShader(tessellationcontrolshader);
		glAttachShader(shader_program, tessellationcontrolshader);

		char* tesse_source = filetobuf(tesse_shader_file);
		tessellationevaluationshader = glCreateShader(GL_TESS_EVALUATION_SHADER);
		glShaderSource(tessellationevaluationshader, 1, (const GLchar **) &tesse_source, 0);
		glCompileShader(tessellationevaluationshader);
		glAttachShader(shader_program, tessellationevaluationshader);
	}

	char* geom_source = filetobuf(geom_shader_file);
	geometryshader = glCreateShader(GL_GEOMETRY_SHADER);
	glShaderSource(geometryshader, 1, (const GLchar **) &geom_source, 0);
	glCompileShader(geometryshader);
	glAttachShader(shader_program, geometryshader);

	char* frag_source = filetobuf(frag_shader_file);
	fragmentshader = glCreateShader(GL_FRAGMENT_SHADER);
	glShaderSource(fragmentshader, 1, (const GLchar **) &frag_source, 0);
	glCompileShader(fragmentshader);
	glAttachShader(shader_program, fragmentshader);

	glLinkProgram(shader_program);

	char text[1000];
	int length;
	glGetProgramInfoLog(shader_program, 1000, &length, text);
	if(length > 0) {
		fprintf(stderr,"Validate Shader program\n%s\n", text);
	}


	//Now for geometry.

	glGenVertexArrays(1, &vao);
	glBindVertexArray(vao);

	glGenBuffers(2, vbo);
	glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
	glBufferData(GL_ARRAY_BUFFER, numverts*sizeof(Vertex), vertices, GL_STATIC_DRAW);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo[1]);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, numelements*sizeof(GLuint), elements, GL_STATIC_DRAW);

	glVertexAttribPointer(0, 3, GL_DOUBLE, GL_FALSE, sizeof(struct Vertex), (GLvoid*)offsetof(struct Vertex, pos));
	glVertexAttribPointer(1, 3, GL_DOUBLE, GL_FALSE, sizeof(struct Vertex), (GLvoid*)offsetof(struct Vertex, norm));
	glEnableVertexAttribArray(0);
	glEnableVertexAttribArray(1);

	glBindVertexArray(0);
	glBindBuffer(GL_ARRAY_BUFFER, 0);


}
	ShaderProgram::ShaderProgram(const char *vertex, const char *fragment, const ShaderFlags &flags)
	{
		File::uptr vs, fs;		
		
		v = glCreateShader(GL_VERTEX_SHADER);
		f = glCreateShader(GL_FRAGMENT_SHADER);
	
		uint64 size;

		vs = File::map(vertex, File::Read, &size);
		std::unique_ptr<char[]> vs1(new char[size + 1]);
		memcpy(vs1.get(), vs.get(), size * sizeof(char));
		vs1[size] = 0;

		fs = File::map(fragment, File::Read, &size);
		std::unique_ptr<char[]> fs1(new char[size + 1]);
		memcpy(fs1.get(), fs.get(), size * sizeof(char));
		fs1[size] = 0;

		//TODO: Może troszkę to ulepszyć... (Chodzi o to, że header trzeba dokleić po #version)
		const char * vv = vs1.get();
		std::string fscode = fs1.get();
		size_t ver = fscode.find("#version");
		ver = fscode.find("\n", ver);
		std::string ffs = fscode.substr(0, ver) + "\n" + flags.getHeader() + fscode.substr(ver + 1);
		const char * ff = ffs.c_str();

		glShaderSource(v, 1, &vv, NULL);
		glShaderSource(f, 1, &ff, NULL);

		GLint status;
		glCompileShader(v);
		glGetShaderiv(v, GL_INFO_LOG_LENGTH, &status);
		std::unique_ptr<GLchar[]> buffer(new GLchar[status]);
		glGetShaderInfoLog(v, status, &status, buffer.get());
		glGetShaderiv(v, GL_COMPILE_STATUS, &status);
		if(status != GL_TRUE)
			RAISE(ShaderException, "Error while compiling Vertex Shader!", buffer.get());
		else
			LOG(errorLogger, "Vertex Shader Info Log:%s\n", buffer.get());

		glCompileShader(f);
		glGetShaderiv(f, GL_INFO_LOG_LENGTH, &status);
		buffer = std::unique_ptr<GLchar[]>(new GLchar[status]);
		glGetShaderInfoLog(f, status, &status, buffer.get());
		glGetShaderiv(f, GL_COMPILE_STATUS, &status);
		if(status != GL_TRUE)
			RAISE(ShaderException, "Error while compiling Fragment Shader!", buffer.get());
		else
			LOG(errorLogger, "Fragment Shader Info Log:%s\n", buffer.get());

		p = glCreateProgram();

		glAttachShader(p, v);
		glAttachShader(p, f);
		
		glLinkProgram(p);

		glValidateProgram(p);

		glGetProgramiv(p, GL_INFO_LOG_LENGTH, &status);
		buffer = std::unique_ptr<GLchar[]>(new GLchar[status]);
		glGetProgramInfoLog(p, status, &status, buffer.get());
		glGetProgramiv(p, GL_VALIDATE_STATUS, &status);
		if(status != GL_TRUE)
			RAISE(ShaderException, "Error while linking / validating Shader Program!", buffer.get());
		else
			LOG(errorLogger, "Shader Program Info Log:%s\n", buffer.get());

		HASSERT(p && v && f);
	}
Esempio n. 18
0
GLuint DepalShaderCache::GetDepalettizeShader(GEBufferFormat pixelFormat) {
	u32 id = GenerateShaderID(pixelFormat);

	auto shader = cache_.find(id);
	if (shader != cache_.end()) {
		return shader->second->program;
	}

	char *buffer = new char[2048];

	if (useGL3_) {
		GenerateDepalShader300(buffer, pixelFormat);
	} else {
		GenerateDepalShader100(buffer, pixelFormat);
	}

	GLuint fragShader = glCreateShader(GL_FRAGMENT_SHADER);

	const char *buf = buffer;
	glShaderSource(fragShader, 1, &buf, 0);
	glCompileShader(fragShader);

	CheckShaderCompileSuccess(fragShader, buffer);

	GLuint program = glCreateProgram();
	glAttachShader(program, vertexShader_);
	glAttachShader(program, fragShader);
	
	glBindAttribLocation(program, 0, "a_position");
	glBindAttribLocation(program, 1, "a_texcoord0");

	glLinkProgram(program);
	glUseProgram(program);

	GLint u_tex = glGetUniformLocation(program, "tex");
	GLint u_pal = glGetUniformLocation(program, "pal");

	glUniform1i(u_tex, 0);
	glUniform1i(u_pal, 1);

	GLint linkStatus = GL_FALSE;
	glGetProgramiv(program, GL_LINK_STATUS, &linkStatus);
	if (linkStatus != GL_TRUE) {
		GLint bufLength = 0;
		glGetProgramiv(program, GL_INFO_LOG_LENGTH, &bufLength);
		if (bufLength) {
			char* errorbuf = new char[bufLength];
			glGetProgramInfoLog(program, bufLength, NULL, errorbuf);
#ifdef SHADERLOG
			OutputDebugStringUTF8(buffer);
			OutputDebugStringUTF8(errorbuf);
#endif
			ERROR_LOG(G3D, "Could not link program:\n %s  \n\n %s", errorbuf, buf);
			delete[] errorbuf;	// we're dead!
		}

		delete[] buffer;
		return 0;
	}

	DepalShader *depal = new DepalShader();
	depal->program = program;
	depal->fragShader = fragShader;

	cache_[id] = depal;

	delete[] buffer;

	return depal->program;
}
Esempio n. 19
0
int main(int argc, char *argv[])
{
    SDL_Surface *screen;
    if ( SDL_Init(SDL_INIT_VIDEO) != 0 ) {
        printf("Unable to initialize SDL: %s\n", SDL_GetError());
        return 1;
    }

    SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );
    screen = SDL_SetVideoMode( 640, 480, 24, SDL_OPENGL );
    if ( !screen ) {
        printf("Unable to set video mode: %s\n", SDL_GetError());
        return 1;
    }
    
    glClearColor( 0, 0, 0, 0 );
    glClear( GL_COLOR_BUFFER_BIT );

    glGenVertexArrays_ =        (PFNGLGENVERTEXARRAYSPROC)     SDL_GL_GetProcAddress("glGenVertexArrays");
    assert(glGenVertexArrays_);
    glBindVertexArray_ =        (PFNGLBINDVERTEXARRAYPROC)     SDL_GL_GetProcAddress("glBindVertexArray");
    assert(glBindVertexArray_);
    glDeleteVertexArrays_ =     (PFNGLDELETEVERTEXARRAYSPROC)     SDL_GL_GetProcAddress("glDeleteVertexArrays");
    assert(glDeleteVertexArrays_);

    glEnableClientState(GL_TEXTURE_COORD_ARRAY); // enabling it *before* the vao does nothing, the vao should wipe it out!

    // Generate a VAO
    GLuint vao;
    glGenVertexArrays_(1, &vao);
    glBindVertexArray_(vao);

    // Create a texture

    GLuint texture;
    glGenTextures( 1, &texture );
    glBindTexture( GL_TEXTURE_2D, texture );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
    GLubyte textureData[16*16*4];
    for (int x = 0; x < 16; x++) {
      for (int y = 0; y < 16; y++) {
        *((int*)&textureData[(x*16 + y) * 4]) = x*16 + ((y*16) << 8);
      }
    }
    glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, 16, 16, 0,
                  GL_RGBA, GL_UNSIGNED_BYTE, textureData );

    // Create a second texture

    GLuint texture2;
    glGenTextures( 1, &texture2 );
    glBindTexture( GL_TEXTURE_2D, texture2 );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
    GLubyte texture2Data[] = { 0xff,    0,    0, 0xff,
                                  0, 0xff,    0, 0xaa,
                                  0,    0, 0xff, 0x55,
                               0x80, 0x90, 0x70,    0 };
    glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, 2, 2, 0,
                  GL_RGBA, GL_UNSIGNED_BYTE, texture2Data );
    
    // BEGIN

#if USE_GLEW
    glewInit();
#endif

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    // original: glFrustum(-0.6435469817188064, 0.6435469817188064 ,-0.48266022190470925, 0.48266022190470925 ,0.5400000214576721, 2048);
    //glFrustum(-0.6435469817188064, 0.1435469817188064 ,-0.48266022190470925, 0.88266022190470925 ,0.5400000214576721, 2048);
    GLfloat pm[] = { 1.372136116027832, 0, 0, 0, 0, 0.7910231351852417, 0, 0, -0.6352481842041016, 0.29297152161598206, -1.0005275011062622, -1, 0, 0, -1.080284833908081, 0 };
    glLoadMatrixf(pm);

    glMatrixMode(GL_MODELVIEW);
    GLfloat matrixData[] = { -1, 0, 0, 0,
                              0, 0,-1, 0,
                              0, 1, 0, 0,
                              0, 0, 0, 1 };
    glLoadMatrixf(matrixData);
    //glTranslated(-512,-512,-527); // XXX this should be uncommented, but if it is then nothing is shown

//    glEnable(GL_CULL_FACE);
  //  glEnable(GL_DEPTH_TEST);

    //glClear(GL_DEPTH_BUFFER_BIT);

//    glEnableClientState(GL_NORMAL_ARRAY);
  //  glEnableClientState(GL_COLOR_ARRAY);

    glActiveTexture(GL_TEXTURE0);

    glEnableClientState(GL_VERTEX_ARRAY);

    GLuint arrayBuffer, elementBuffer;
    glGenBuffers(1, &arrayBuffer);
    glGenBuffers(1, &elementBuffer);

    GLubyte arrayData[] = {
/*
[0, 0,   0, 67] ==>  128 float
[0, 0, 128, 67] ==>  256 float
[0, 0,   0, 68] ==>  512 float
[0, 0, 128, 68] ==> 1024 float

[vertex x        ] [vertex y         ] [vertex z         ] [nr]                [texture u        ] [texture v        ] [lm u   ] [lm v   ] [color r,g,b,a    ] */
  0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128, //  0
  0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,  67,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128, //  1
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,  67,   0,   0,   0,  67,   0,   0,   0,   0, 128, 128, 128, 128, //  2
  0,   0,   0,   0,   0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,  67,   0,   0,   0,   0, 128, 128, 128, 128, //  3
  0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,  67,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128, //  4
  0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0, 128,  67,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128, //  5
  0,   0, 128,  68,   0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0, 128,  67,   0,   0,   0,  67,   0,   0,   0,   0, 128, 128, 128, 128, //  6
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,  67,   0,   0,   0,  67,   0,   0,   0,   0, 128, 128, 128, 128, //  7
  0,   0,   0,   0,   0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,  67,   0,   0,   0,   0, 128, 128, 128, 128, //  8
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,  67,   0,   0,   0,  67,   0,   0,   0,   0, 128, 128, 128, 128, //  9
  0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,  67,   0,   0, 128,  67,   0,   0,   0,   0, 128, 128, 128, 128, // 10
  0,   0,   0,   0,   0,   0, 128,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128,  67,   0,   0,   0,   0, 128, 128, 128, 128, // 11
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,  67,   0,   0,   0,  67,   0,   0,   0,   0, 128, 128, 128, 128, // 12
  0,   0, 128,  68,   0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0, 128,  67,   0,   0,   0,  67,   0,   0,   0,   0, 128, 128, 128, 128, // 13
  0,   0, 128,  68,   0,   0, 128,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0, 128,  67,   0,   0, 128,  67,   0,   0,   0,   0, 128, 128, 128, 128, // 14
  0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,  67,   0,   0, 128,  67,   0,   0,   0,   0, 128, 128, 128, 128, // 15

  0,   0,   0,  68,   0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,   0,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,   0,   0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,   0,   0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,   0,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0, 128,  68,   0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0, 128,  68,   0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0, 128,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,   0,   0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,   0,   0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,   0,   0,   0, 128,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0, 128,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0, 128,  68,   0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0, 128,  68,   0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0, 128,  68,   0,   0, 128,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128
    };
    assert(sizeof(arrayData) == 1408);
    glBindBuffer(GL_ARRAY_BUFFER, arrayBuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(arrayData), arrayData, GL_STATIC_DRAW);
    glBindBuffer(GL_ARRAY_BUFFER, 0);

    GLushort elementData[] = { 1, 2, 0, 2, 3, 0, 5, 6, 4, 6, 7, 4, 9, 10, 8, 10, 11, 8, 13, 14, 12, 14, 15, 12 };
    assert(sizeof(elementData) == 48);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementBuffer);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elementData), elementData, GL_STATIC_DRAW);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

    glBindBuffer(GL_ARRAY_BUFFER, arrayBuffer);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementBuffer);

    // sauer vertex data is apparently 0-12: V3F, 12: N1B, 16-24: T2F, 24-28: T2S, 28-32: C4B
    glVertexPointer(3, GL_FLOAT, 32, (void*)0); // all these apply to the ARRAY_BUFFER that is bound
    glTexCoordPointer(2, GL_FLOAT, 32, (void*)16);
//    glClientActiveTexture(GL_TEXTURE1); // XXX seems to be ignored in native build
//    glTexCoordPointer(2, GL_SHORT, 32, (void*)24);
//    glClientActiveTexture(GL_TEXTURE0); // likely not needed, it is a cleanup
//    glNormalPointer(GL_BYTE, 32, (void*)12);
//    glColorPointer(4, GL_UNSIGNED_BYTE, 32, (void*)28);

    glBindTexture(GL_TEXTURE_2D, texture); // diffuse?
    glActiveTexture(GL_TEXTURE0);
    glActiveTexture(GL_TEXTURE1);
    glBindTexture(GL_TEXTURE_2D, texture2); // lightmap?
    glActiveTexture(GL_TEXTURE0);

    GLint ok;

    const char *vertexShader = "uniform mat4 u_modelView;\n"
                               "uniform mat4 u_projection;\n"
                               "varying vec4 v_texCoord0;\n"
                               "void main(void)\n"
                               "{\n" // (gl_ProjectionMatrix * gl_ModelViewMatrix * gl_Vertex)
                                     // (u_projection * u_modelView * a_position)
                               "    gl_Position = (u_projection * u_modelView * gl_Vertex) + vec4(200, 0, 0, 0);\n"
                               "    v_texCoord0.xy = gl_MultiTexCoord0.xy/20.0;\n" // added /100 here
                               "}\n";
    const char *fragmentShader = "uniform sampler2D diffusemap;\n"
                                 "varying vec4 v_texCoord0;\n"
                                 "void main(void)\n"
                                 "{\n"
                                 "    vec4 diffuse = texture2D(diffusemap, v_texCoord0.xy);\n"
                                 "    gl_FragColor = diffuse;\n"
                                 "}\n";

    GLuint vs = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vs, 1, &vertexShader, NULL);
    glCompileShader(vs);
    glGetShaderiv(vs, GL_COMPILE_STATUS, &ok);
    if (!ok) {
      printf("Shader compilation error with vertex\n");
      GLint infoLen = 0;
      glGetShaderiv (vs, GL_INFO_LOG_LENGTH, &infoLen);
      if (infoLen > 1)
      {
         char* infoLog = (char *)malloc(sizeof(char) * infoLen+1);
         glGetShaderInfoLog(vs, infoLen, NULL, infoLog);
         printf("Error compiling shader:\n%s\n", infoLog);            
      }
    }

    GLuint fs = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fs, 1, &fragmentShader, NULL);
    glCompileShader(fs);
    glGetShaderiv(fs, GL_COMPILE_STATUS, &ok);
    if (!ok) {
      printf("Shader compilation error with fragment\n");
      GLint infoLen = 0;
      glGetShaderiv (vs, GL_INFO_LOG_LENGTH, &infoLen);
      if (infoLen > 1)
      {
         char* infoLog = (char *)malloc(sizeof(char) * infoLen+1);
         glGetShaderInfoLog(vs, infoLen, NULL, infoLog);
         printf("Error compiling shader:\n%s\n", infoLog);            
      }
    }

    GLuint program = glCreateProgram();

    glAttachShader(program, vs);
    glAttachShader(program, fs);
    glLinkProgram(program);
    glGetProgramiv(program, GL_LINK_STATUS, &ok);
    assert(ok);

    glUseProgram(program);

    //GLint lightmapLocation = glGetUniformLocation(program, "lightmap");
    //assert(lightmapLocation >= 0);
    //glUniform1i(lightmapLocation, 1); // sampler2D? Is it the texture unit?

    GLint diffusemapLocation = glGetUniformLocation(program, "diffusemap");
    assert(diffusemapLocation >= 0);
    glUniform1i(diffusemapLocation, 0);

    //GLint texgenscrollLocation = glGetUniformLocation(program, "texgenscroll");
    //assert(texgenscrollLocation >= 0);

    //GLint colorparamsLocation = glGetUniformLocation(program, "colorparams");
    //assert(colorparamsLocation >= 0);

    //GLfloat texgenscrollData[] = { 0, 0, 0, 0 };
    //glUniform4fv(texgenscrollLocation, 1, texgenscrollData);

    //GLfloat colorparamsData[] = { 2, 2, 2, 1 };
    //glUniform4fv(colorparamsLocation, 1, colorparamsData);

    {
      GLfloat data[16];
      glGetFloatv(GL_MODELVIEW_MATRIX, data);
      printf("Modelview: ");
      for (int i = 0; i < 16; i++) printf("%.3f, ", data[i]);
      printf("\n");
      //memset(data, 0, 16*4);
      GLint modelViewLocation = glGetUniformLocation(program, "u_modelView");
      assert(modelViewLocation >= 0);
      glUniformMatrix4fv(modelViewLocation, 1, GL_FALSE, data);
    }
    {
      GLfloat data[16];
      glGetFloatv(GL_PROJECTION_MATRIX, data);
      printf("Projection: ");
      for (int i = 0; i < 16; i++) printf("%.3f, ", data[i]);
      printf("\n");
      //memset(data, 0, 16*4);
      GLint projectionLocation = glGetUniformLocation(program, "u_projection");
      assert(projectionLocation >= 0);
      glUniformMatrix4fv(projectionLocation, 1, GL_FALSE, data);
    }

/*
    glBindAttribLocation(program, 0, "a_position");
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 32, (void*)0);
    glEnableVertexAttribArray(0);

    glBindAttribLocation(program, 1, "v_texCoord0");
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 32, (void*)16);
    glEnableVertexAttribArray(1);
*/

    // stop recording in the VAO

    glBindVertexArray_(0);

    // unbind all the stuff the VAO would save for us, so this is a valid test

    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
    glDisableClientState(GL_VERTEX_ARRAY);

    // draw with VAO

    glBindVertexArray_(vao);

    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (void*)12);
    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (void*) 0);
    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (void*)24);
    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (void*)36);

    // END

    SDL_GL_SwapBuffers();

#if !EMSCRIPTEN
    SDL_Delay(1500);
#endif

 //   SDL_Quit();
    
    return 0;
}
Esempio n. 20
0
JNIEXPORT void JNICALL Java_org_lwjgl_opengl_GL20_nglLinkProgram(JNIEnv *env, jclass clazz, jint program, jlong function_pointer) {
	glLinkProgramPROC glLinkProgram = (glLinkProgramPROC)((intptr_t)function_pointer);
	glLinkProgram(program);
}
Esempio n. 21
0
bool ProgramShaderCache::CompileShader ( SHADER& shader, const char* vcode, const char* pcode )
{
	GLuint vsid = CompileSingleShader(GL_VERTEX_SHADER, vcode);
	GLuint psid = CompileSingleShader(GL_FRAGMENT_SHADER, pcode);

	if (!vsid || !psid)
	{
		glDeleteShader(vsid);
		glDeleteShader(psid);
		return false;
	}

	GLuint pid = shader.glprogid = glCreateProgram();;

	glAttachShader(pid, vsid);
	glAttachShader(pid, psid);

	if (g_ogl_config.bSupportsGLSLCache)
		glProgramParameteri(pid, GL_PROGRAM_BINARY_RETRIEVABLE_HINT, GL_TRUE);

	shader.SetProgramBindings();

	glLinkProgram(pid);

	// original shaders aren't needed any more
	glDeleteShader(vsid);
	glDeleteShader(psid);

	GLint linkStatus;
	glGetProgramiv(pid, GL_LINK_STATUS, &linkStatus);
	GLsizei length = 0;
	glGetProgramiv(pid, GL_INFO_LOG_LENGTH, &length);
	if (linkStatus != GL_TRUE || (length > 1 && DEBUG_GLSL))
	{
		GLsizei charsWritten;
		GLchar* infoLog = new GLchar[length];
		glGetProgramInfoLog(pid, length, &charsWritten, infoLog);
		ERROR_LOG(VIDEO, "Program info log:\n%s", infoLog);
		char szTemp[MAX_PATH];
		sprintf(szTemp, "%sbad_p_%d.txt", File::GetUserPath(D_DUMP_IDX).c_str(), num_failures++);
		std::ofstream file;
		OpenFStream(file, szTemp, std::ios_base::out);
		file << s_glsl_header << vcode << s_glsl_header << pcode << infoLog;
		file.close();

		if (linkStatus != GL_TRUE)
			PanicAlert("Failed to link shaders!\nThis usually happens when trying to use Dolphin with an outdated GPU or integrated GPU like the Intel GMA series.\n\nIf you're sure this is Dolphin's error anyway, post the contents of %s along with this error message at the forums.\n\nDebug info (%s, %s, %s):\n%s",
				szTemp,
				g_ogl_config.gl_vendor,
				g_ogl_config.gl_renderer,
				g_ogl_config.gl_version,
				infoLog);

		delete [] infoLog;
	}
	if (linkStatus != GL_TRUE)
	{
		// Compile failed
		ERROR_LOG(VIDEO, "Program linking failed; see info log");

		// Don't try to use this shader
		glDeleteProgram(pid);
		return false;
	}

	shader.SetProgramVariables();

	return true;
}
Esempio n. 22
0
// Create a GLSL program object from vertex and fragment shader files
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;
}
Esempio n. 23
0
        bool Shaders::load()
        {
            /* Creating the vertex shader */
            m_vertex = glCreateShader(GL_VERTEX_SHADER);
            if(glIsShader(m_vertex) != GL_TRUE) {
                core::logger::logm("Couldn't create vertex shader.", core::logger::WARNING);
                return false;
            }
            glShaderSource(m_vertex, 1, &vertexSrc, NULL);

            /* Compiling the vertex shader */
            glCompileShader(m_vertex);
            GLint result;
            glGetShaderiv(m_vertex, GL_COMPILE_STATUS, &result);
            if(result != GL_TRUE) {
                core::logger::logm("Couldn't compile vertex shader.", core::logger::WARNING);
                logCompileError(m_vertex);
                return false;
            }

            /* Creating the fragment shader */
            m_fragment = glCreateShader(GL_FRAGMENT_SHADER);
            if(glIsShader(m_fragment) != GL_TRUE) {
                core::logger::logm("Couldn't create fragment shader.", core::logger::WARNING);
                return false;
            }
            glShaderSource(m_fragment, 1, &fragmentSrc, NULL);

            /* Compiling the fragment shader */
            glCompileShader(m_fragment);
            glGetShaderiv(m_fragment, GL_COMPILE_STATUS, &result);
            if(result != GL_TRUE) {
                core::logger::logm("Couldn't compile fragment shader.", core::logger::WARNING);
                logCompileError(m_fragment);
                return false;
            }

            /* Creating the openGL program */
            m_program = glCreateProgram();
            if(m_program == 0) {
                core::logger::logm("Couldn't create the shader program.", core::logger::WARNING);
                return false;
            }

            /* Attaching the shaders to the program */
            glAttachShader(m_program, m_vertex);
            glAttachShader(m_program, m_fragment);

            /* Linking the program */
            glLinkProgram(m_program);
            glGetProgramiv(m_program, GL_LINK_STATUS, &result);
            if(result != GL_TRUE) {
                core::logger::logm("Couldn't link the shader program.", core::logger::WARNING);
                GLint logsize;
                glGetProgramiv(m_program, GL_INFO_LOG_LENGTH, &logsize);
                if(logsize > 0) {
                    char* log = new char [logsize];
                    glGetProgramInfoLog(m_program, logsize, &logsize, log);
                    log[logsize - 1] = '\0';
                    std::ostringstream oss;
                    oss << "Error while linking a shader program \"" << log << "\"";
                    core::logger::logm(oss.str(), core::logger::MSG);
                    delete[] log;
                }
                return false;
            }
            glUseProgram(m_program);

            /* Getting the uniforms */
            if(!loadUniform(&m_text, "texture")) return false;

            /* Preparing the texture */
            GLint tex = -1;
            if(!loadUniform(&tex, "tex")) return false;
            glUniform1i(tex, 0);

            return true;
        }
Esempio n. 24
0
int main()
{
    int width = 640;
    int height = 480;
    
    if(glfwInit() == GL_FALSE)
    {
        std::cerr << "failed to init GLFW" << std::endl;
        return 1;
    } 
    glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 4);
    glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 3);
 
    // create a window
    if(glfwOpenWindow(width, height, 0, 0, 0, 8, 24, 8, GLFW_WINDOW) == GL_FALSE)
    {
        std::cerr << "failed to open window" << std::endl;
        glfwTerminate();
        return 1;
    }
    
    // setup windows close callback
    glfwSetWindowCloseCallback(closedWindow);
    
    if (gl3wInit())
    {
        std::cerr << "failed to init GL3W" << std::endl;
        glfwCloseWindow();
        glfwTerminate();
        return 1;
    }

    // shader source code
    
    // the vertex shader simply passes through data
    std::string vertex_source =
        "#version 430\n"
        "layout(location = 0) in vec4 vposition;\n"
        "void main() {\n"
        "   gl_Position = vposition;\n"
        "}\n";
    
    // the geometry shader creates the billboard quads
    std::string geometry_source =
        "#version 430\n"
        "uniform mat4 View;\n"
        "uniform mat4 Projection;\n"
        "layout (points) in;\n"
        "layout (triangle_strip, max_vertices = 4) out;\n"
        "out vec2 txcoord;\n"
        "void main() {\n"
        "   vec4 pos = View*gl_in[0].gl_Position;\n"
        "   txcoord = vec2(-1,-1);\n"
        "   gl_Position = Projection*(pos+0.2*vec4(txcoord,0,0));\n"
        "   EmitVertex();\n"
        "   txcoord = vec2( 1,-1);\n"
        "   gl_Position = Projection*(pos+0.2*vec4(txcoord,0,0));\n"
        "   EmitVertex();\n"
        "   txcoord = vec2(-1, 1);\n"
        "   gl_Position = Projection*(pos+0.2*vec4(txcoord,0,0));\n"
        "   EmitVertex();\n"
        "   txcoord = vec2( 1, 1);\n"
        "   gl_Position = Projection*(pos+0.2*vec4(txcoord,0,0));\n"
        "   EmitVertex();\n"
        "}\n";    
    
    // the fragment shader creates a bell like radial color distribution    
    std::string fragment_source =
        "#version 330\n"
        "in vec2 txcoord;\n"
        "layout(location = 0) out vec4 FragColor;\n"
        "void main() {\n"
        "   float s = 0.2*(1/(1+15.*dot(txcoord, txcoord))-1/16.);\n"
        "   FragColor = s*vec4(0.3,0.3,1.0,1);\n"
        "}\n";
   
    // program and shader handles
    GLuint shader_program, vertex_shader, geometry_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 geometry shader
    geometry_shader = glCreateShader(GL_GEOMETRY_SHADER);
    source = geometry_source.c_str();
    length = geometry_source.size();
    glShaderSource(geometry_shader, 1, &source, &length); 
    glCompileShader(geometry_shader);
    if(!check_shader_compile_status(geometry_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, geometry_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 View_location = glGetUniformLocation(shader_program, "View");
    GLint Projection_location = glGetUniformLocation(shader_program, "Projection");

    std::string compute_source =
        "#version 430\n"
        "layout(local_size_x=256) in;\n"
        
        "uniform vec3 center[3];\n"
        "uniform float radius[3];\n"
        "uniform vec3 g;\n"
        "uniform float dt;\n"
        "uniform float bounce;\n"
        "uniform int seed;\n"
        "uniform layout(rgba32f) imageBuffer particles;\n"
                
        "float hash(int x) {\n"
        "   x = x*1235167 + int(gl_GlobalInvocationID)*948737 + seed*9284365;\n"
        "   x = (x >> 13) ^ x;\n"
        "   return ((x * (x * x * 60493 + 19990303) + 1376312589) & 0x7fffffff)/float(0x7fffffff-1);\n"
        "}\n"
        
        "void main() {\n"
        "   int index = int(gl_GlobalInvocationID);\n"
        "   vec3 inposition = imageLoad(particles, 2*index).xyz;\n"
        "   vec3 invelocity = imageLoad(particles, 2*index+1).xyz;\n"
        "   vec3 outvelocity = invelocity;\n"
        "   for(int j = 0;j<3;++j) {\n"
        "       vec3 diff = inposition-center[j];\n"
        "       float dist = length(diff);\n"
        "       float vdot = dot(diff, invelocity);\n"
        "       if(dist<radius[j] && vdot<0.0)\n"
        "           outvelocity -= bounce*diff*vdot/(dist*dist);\n"
        "   }\n"
        "   outvelocity += dt*g;\n"
        "   vec3 outposition = inposition + dt*outvelocity;\n"
        "   if(outposition.y < -30.0)\n"
        "   {\n"
        "       outvelocity = vec3(0,0,0);\n"
        "       outposition = 0.5-vec3(hash(3*index+0),hash(3*index+1),hash(3*index+2));\n"
        "       outposition = vec3(0,20,0) + 5.0*outposition;\n"
        "   }\n"
        "   imageStore(particles, 2*index, vec4(outposition,1));\n"
        "   imageStore(particles, 2*index+1, vec4(outvelocity,1));\n"
        "}\n";
   
    // program and shader handles
    GLuint compute_program, compute_shader;

    // create and compiler vertex shader
    compute_shader = glCreateShader(GL_COMPUTE_SHADER);
    source = compute_source.c_str();
    length = compute_source.size();
    glShaderSource(compute_shader, 1, &source, &length); 
    glCompileShader(compute_shader);
    if(!check_shader_compile_status(compute_shader))
    {
        return 1;
    }

    // create program
    compute_program = glCreateProgram();
    
    // attach shaders
    glAttachShader(compute_program, compute_shader);
   
    // link the program and check for errors
    glLinkProgram(compute_program);
    check_program_link_status(compute_program);

    GLint center_location = glGetUniformLocation(compute_program, "center");
    GLint radius_location = glGetUniformLocation(compute_program, "radius");
    GLint g_location = glGetUniformLocation(compute_program, "g");
    GLint dt_location = glGetUniformLocation(compute_program, "dt");
    GLint bounce_location = glGetUniformLocation(compute_program, "bounce");
    GLint seed_location = glGetUniformLocation(compute_program, "seed");
    GLint particles_location = glGetUniformLocation(compute_program, "particles");
   
    const int particles = 128*1024;

    // randomly place particles in a cube
    std::vector<glm::vec4> vertexData(2*particles);
    for(int i = 0;i<particles;++i)
    {
        // initial position
        vertexData[2*i+0] = glm::vec4(
                                0.5f-float(std::rand())/RAND_MAX,
                                0.5f-float(std::rand())/RAND_MAX,
                                0.5f-float(std::rand())/RAND_MAX,
                                0
                            );
        vertexData[2*i+0] = glm::vec4(0.0f,20.0f,0.0f,1) + 5.0f*vertexData[2*i+0];
        
        // initial velocity
        vertexData[2*i+1] = glm::vec4(0,0,0,0);
    }
    
    // generate vbos and vaos
    GLuint vao, vbo;
    glGenVertexArrays(1, &vao);
    glGenBuffers(1, &vbo);
    

    glBindVertexArray(vao);
        
    glBindBuffer(GL_ARRAY_BUFFER, vbo);

    // fill with initial data
    glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec4)*vertexData.size(), &vertexData[0], GL_STATIC_DRAW);
                        
    // set up generic attrib pointers
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 8*sizeof(GLfloat), (char*)0 + 0*sizeof(GLfloat));
    // set up generic attrib pointers
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 8*sizeof(GLfloat), (char*)0 + 4*sizeof(GLfloat));


    // "unbind" vao
    glBindVertexArray(0);
    
    // texture handle
    GLuint buffer_texture;
    
    // generate and bind the buffer texture
    glGenTextures(1, &buffer_texture);
    glBindTexture(GL_TEXTURE_BUFFER, buffer_texture);
    
    // tell the buffer texture to use 
    glTexBuffer(GL_TEXTURE_BUFFER, GL_RGBA32F, vbo);
    
    
    
    // we are blending so no depth testing
    glDisable(GL_DEPTH_TEST);
    
    // enable blending
    glEnable(GL_BLEND);
    //  and set the blend function to result = 1*source + 1*destination
    glBlendFunc(GL_ONE, GL_ONE);

    // define spheres for the particles to bounce off
    const int spheres = 3;
    glm::vec3 center[spheres];
    float radius[spheres];
    center[0] = glm::vec3(0,12,1);
    radius[0] = 3;
    center[1] = glm::vec3(-3,0,0);
    radius[1] = 7;
    center[2] = glm::vec3(5,-10,0);
    radius[2] = 12;

    // physical parameters
    float dt = 1.0f/60.0f;
    glm::vec3 g(0.0f, -9.81f, 0.0f);
    float bounce = 1.2f; // inelastic: 1.0f, elastic: 2.0f

    int current_buffer=0;
    running = true;
    while(running)
    {   
        // get the time in seconds
        float t = glfwGetTime();
        
        // terminate on excape 
        if(glfwGetKey(GLFW_KEY_ESC))
        {
            running = false;
        }



        // use the transform shader program
        glUseProgram(compute_program);

        // set the uniforms
        glUniform3fv(center_location, 3, reinterpret_cast<GLfloat*>(center)); 
        glUniform1fv(radius_location, 3, reinterpret_cast<GLfloat*>(radius));
        glUniform3fv(g_location, 1, glm::value_ptr(g));
        glUniform1f(dt_location, dt);
        glUniform1f(bounce_location, bounce);
        glUniform1i(seed_location, std::rand());
        
        glBindImageTexture(0, buffer_texture, 0, GL_FALSE, 0, GL_READ_WRITE, GL_RGBA32F);
        glUniform1i(particles_location, 0);

        glDispatchCompute(particles/256, 1, 1);

        
        // 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, -30.0f));
        
        // make the camera rotate around the origin
        View = glm::rotate(View, 30.0f, glm::vec3(1.0f, 0.0f, 0.0f)); 
        View = glm::rotate(View, -22.5f*t, glm::vec3(0.0f, 1.0f, 0.0f)); 
        
        // set the uniform
        glUniformMatrix4fv(View_location, 1, GL_FALSE, glm::value_ptr(View)); 
        glUniformMatrix4fv(Projection_location, 1, GL_FALSE, glm::value_ptr(Projection)); 
        
        // bind the current vao
        glBindVertexArray(vao);

        // draw
        glDrawArrays(GL_POINTS, 0, particles);
       
        // check for errors
        GLenum error = glGetError();
        if(error != GL_NO_ERROR)
        {
            std::cerr << gluErrorString(error);
            running = false;       
        }
        
        // finally swap buffers
        glfwSwapBuffers();
    }
    
    // delete the created objects
        
    glDeleteVertexArrays(1, &vao);
    glDeleteBuffers(1, &vbo);
    glDeleteTextures(1, &buffer_texture);
    
    glDetachShader(shader_program, vertex_shader);	
    glDetachShader(shader_program, geometry_shader);	
    glDetachShader(shader_program, fragment_shader);
    glDeleteShader(vertex_shader);
    glDeleteShader(geometry_shader);
    glDeleteShader(fragment_shader);
    glDeleteProgram(shader_program);

    glDetachShader(compute_program, compute_shader);	
    glDeleteShader(compute_shader);
    glDeleteProgram(compute_program);
    
    glfwCloseWindow();
    glfwTerminate();
    return 0;
}
Esempio n. 25
0
bool initProgram()
{
	bool Validated = true;
	GLint Success = 0;

	glGenProgramPipelines(1, &PipelineName);
	glBindProgramPipeline(PipelineName);
	glBindProgramPipeline(0);

	ProgramName[program::VERT] = glCreateProgram();
	glProgramParameteri(ProgramName[program::VERT], GL_PROGRAM_SEPARABLE, GL_TRUE);
	glProgramParameteri(ProgramName[program::VERT], GL_PROGRAM_BINARY_RETRIEVABLE_HINT, GL_TRUE);

	{
		GLenum Format = 0;
		GLint Size = 0;
		std::vector<glm::byte> Data;
		if(glf::loadBinary(VERT_PROGRAM_BINARY, Format, Data, Size))
		{
			glProgramBinary(ProgramName[program::VERT], Format, &Data[0], Size);
			glGetProgramiv(ProgramName[program::VERT], GL_LINK_STATUS, &Success);
		}
	}

	// Create program
	if(Validated && !Success)
	{
		GLuint VertShaderName = glf::createShader(GL_VERTEX_SHADER, VERT_SHADER_SOURCE);

		glAttachShader(ProgramName[program::VERT], VertShaderName);
		glDeleteShader(VertShaderName);
		glLinkProgram(ProgramName[program::VERT]);
		Validated = Validated && glf::checkProgram(ProgramName[program::VERT]);
	}

	ProgramName[program::FRAG] = glCreateProgram();
	glProgramParameteri(ProgramName[program::FRAG], GL_PROGRAM_SEPARABLE, GL_TRUE);
	glProgramParameteri(ProgramName[program::FRAG], GL_PROGRAM_BINARY_RETRIEVABLE_HINT, GL_TRUE);

	{
		GLenum Format = 0;
		GLint Size = 0;
		std::vector<glm::byte> Data;
		if(glf::loadBinary(FRAG_PROGRAM_BINARY, Format, Data, Size))
		{
			glProgramBinary(ProgramName[program::FRAG], Format, &Data[0], Size);
			glGetProgramiv(ProgramName[program::FRAG], GL_LINK_STATUS, &Success);
		}
	}

	// Create program
	if(Validated && !Success)
	{
		GLuint FragShaderName = glf::createShader(GL_FRAGMENT_SHADER, FRAG_SHADER_SOURCE);

		glAttachShader(ProgramName[program::FRAG], FragShaderName);
		glDeleteShader(FragShaderName);
		glLinkProgram(ProgramName[program::FRAG]);
		Validated = Validated && glf::checkProgram(ProgramName[program::FRAG]);
	}

	if(Validated)
	{
		glUseProgramStages(PipelineName, GL_VERTEX_SHADER_BIT, ProgramName[program::VERT]);
		glUseProgramStages(PipelineName, GL_FRAGMENT_SHADER_BIT, ProgramName[program::FRAG]);
		Validated = Validated && glf::checkError("initProgram - stage");
	}

	// Get variables locations
	if(Validated)
	{
		UniformMVP = glGetUniformLocation(ProgramName[program::VERT], "MVP");
		UniformDiffuse = glGetUniformLocation(ProgramName[program::FRAG], "Diffuse");
	}

	return Validated && glf::checkError("initProgram");
}
Esempio n. 26
0
int main(void)
{
    DemoGame game = DemoGame();

    resultv rv = game.initialize({
        800, // Width
        600, // Height
        "Open GL", // Window name
        true // Windowed?
    });

    if (GR_FAILED(rv)) {
        ERR("Failed to initialize %d", rv);
        return 1;
    }


    static GLfloat vertices[] = {
     -1.0f,-1.0f,-1.0f, // triangle 1 : begin
     -1.0f,-1.0f, 1.0f,
     -1.0f, 1.0f, 1.0f // triangle 1 : end
    };

    grapl::gfx::Mesh mesh = grapl::gfx::Mesh(vertices, sizeof(vertices));
    mesh.init();

    // Compile shaders
    const GLchar* vertShader =
        "#version 150 core\n"
        "in vec2 position;"
        "void main() {"
        "   gl_Position = vec4(position, 0.0, 1.0);"
        "}";

    const GLchar* fragShader =
        "#version 150 core\n"
        "out vec4 outColor;"
        "void main() {"
        "  outColor = vec4(1.0, 1.0, 1.0, 1.0);"
        "}";

    // TODO: Error handling

    std::unique_ptr<OpenGLShader> vertexShaderObject(new OpenGLShader(vertShader, GL_VERTEX_SHADER));
    std::unique_ptr<OpenGLShader> fragmentShaderObject(new OpenGLShader(fragShader, GL_FRAGMENT_SHADER));

    vertexShaderObject->compile();
    fragmentShaderObject->compile();
    GLuint shaderProgram = glCreateProgram();
    glAttachShader(shaderProgram, vertexShaderObject->mGLResource);
    glAttachShader(shaderProgram, fragmentShaderObject->mGLResource);

    // Bind the output to the correct buffer (should happen before linking)
    glBindFragDataLocation(shaderProgram, 0, "outColor");

    glLinkProgram(shaderProgram);
    glUseProgram(shaderProgram);

    // Get a reference to the "position" input of the vertex shader
    GLint positionAttribute = glGetAttribLocation(shaderProgram, "position");
    glEnableVertexAttribArray(positionAttribute);

    glVertexAttribPointer(positionAttribute,
                        /* number of inputs/components in vec */
                        2,
                        /* Type of each component */
                        GL_FLOAT,
                        /* Normalize between -1.0 and 1.0? */
                        GL_FALSE,
                        /* The "stride" */
                        0,
                        /* The offset */
                        0);


    /* The stride is the number of bytes between each position attribute in the
     * array, the value of 0 means there is no data between each vertex
     *
     * The offset is the value from the start of the array where the position
     * begins
     */

    game.run();

    glDeleteProgram(shaderProgram);
    return 0;
}
Esempio n. 27
0
// The MAIN function, from here we start the application and run the game loop
int main()
{
    // Init GLFW
    glfwInit();
    // Set all the required options for GLFW
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_ANY_PROFILE);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

    // Create a GLFWwindow object that we can use for GLFW's functions
    GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr);
    glfwMakeContextCurrent(window);

    // Set the required callback functions
    glfwSetKeyCallback(window, key_callback);

    // Set this to true so GLEW knows to use a modern approach to retrieving function pointers and extensions
    glewExperimental = GL_TRUE;
    // Initialize GLEW to setup the OpenGL Function pointers
    glewInit();

    // Define the viewport dimensions
    glViewport(0, 0, WIDTH, HEIGHT);


    // Build and compile our shader program
    // Vertex shader
    GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
    glCompileShader(vertexShader);
    // Check for compile time errors
    GLint success;
    GLchar infoLog[512];
    glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
    if (!success)
    {
        glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
        std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;
    }
    // Fragment shader
    GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
    glCompileShader(fragmentShader);
    // Check for compile time errors
    glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);
    if (!success)
    {
        glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog);
        std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::endl;
    }
    // Link shaders
    GLuint shaderProgram = glCreateProgram();
    glAttachShader(shaderProgram, vertexShader);
    glAttachShader(shaderProgram, fragmentShader);
    glLinkProgram(shaderProgram);
    // Check for linking errors
    glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
    if (!success) {
        glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);
        std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << std::endl;
    }
    glDeleteShader(vertexShader);
    glDeleteShader(fragmentShader);


    // Set up vertex data (and buffer(s)) and attribute pointers
    GLfloat first_vertices[] = {
        -0.5f, -0.5f, 0.0f, // Left  
         0.5f, -0.5f, 0.0f, // Right 
         0.0f,  0.5f, 0.0f
	};
	// Top  
	GLfloat second_vertices[] ={
		 -1.0f, -1.0f, 0.0f,
		 -0.5f, -0.5f, 0.0f,
		 -0.75f, 0.5f, 0.0f
    };

    GLuint VBOs[2], VAOs[2];
    glGenVertexArrays(2, VAOs);
	
    glGenBuffers(2, VBOs);

    // First Triangle
    glBindVertexArray(VAOs[0]);
	glBindBuffer(GL_ARRAY_BUFFER, VBOs[0]);
	glBufferData(GL_ARRAY_BUFFER, sizeof(first_vertices), first_vertices, GL_STATIC_DRAW);
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0);
    glEnableVertexAttribArray(0);
	glBindVertexArray(VAOs[0]);

   //second triangle
	glBindVertexArray(VAOs[1]);
	glBindBuffer(GL_ARRAY_BUFFER, VBOs[1]);
	glBufferData(GL_ARRAY_BUFFER, sizeof(second_vertices), second_vertices, GL_STATIC_DRAW);
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0);
    glEnableVertexAttribArray(0);
	glBindVertexArray(VAOs[1]);
    

    

    glBindBuffer(GL_ARRAY_BUFFER, 0); // Note that this is allowed, the call to glVertexAttribPointer registered VBO as the currently bound vertex buffer object so afterwards we can safely unbind

    glBindVertexArray(0); // Unbind VAO (it's always a good thing to unbind any buffer/array to prevent strange bugs)

    // Game loop
    while (!glfwWindowShouldClose(window))
    {
        // Check if any events have been activiated (key pressed, mouse moved etc.) and call corresponding response functions
        glfwPollEvents();

        // Render
        // Clear the colorbuffer
        glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);

        // Draw our first triangle
        glUseProgram(shaderProgram);
        glBindVertexArray(VAOs[0]);
        glDrawArrays(GL_TRIANGLES, 0, 3);
		

		glBindVertexArray(VAOs[1]);
        glDrawArrays(GL_TRIANGLES, 0, 3);
		glBindVertexArray(0);

        // Swap the screen buffers
        glfwSwapBuffers(window);
    }
    // Properly de-allocate all resources once they've outlived their purpose
    
	glDeleteVertexArrays(2, VAOs);
    
	glDeleteBuffers(2, VBOs);
    // Terminate GLFW, clearing any resources allocated by GLFW.
    glfwTerminate();
    return 0;
}
Esempio n. 28
0
int Init ( void )
{
   GLuint vertexShader;
   GLuint fragmentShader;
   GLuint programObject;
   GLint linked;

   // Load Textures
   glGenTextures(TEXTURE_COUNT, GtextureID);
   loadTexture("../media/rocks.bmp", GtextureID[0]);
   loadTexture("../media/rainbow-blocks.bmp", GtextureID[1]);
   loadTexture("../media/rgb.bmp", GtextureID[2]);
   loadTexture("../media/barack-obama.bmp", GtextureID[3]);
   loadTexture("../media/rainbow-stripes.bmp", GtextureID[4]);
   loadTexture("../media/gtx-promo.bmp", GtextureID[5]);
   loadTexture("../media/Mettle_Skybox_Cubic_Cross.bmp", GtextureID[6]);
   loadTexture("../media/sky.bmp", GtextureID[7]);

   // Initialize FMOD
   //initFmod();

   // Create a new FBO (Frame Bufffer Object)
   glGenFramebuffers(1, &Gframebuffer);

   // Create a new empty texture for rendering original scene
   glGenTextures(1, &GfullscreenTexture);
   glBindTexture(GL_TEXTURE_2D, GfullscreenTexture);
   glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, WINDOW_WIDTH, WINDOW_HEIGHT, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

   // Create 3 new empty textures for processing textures
   glGenTextures(1, &GpTexture_0);
   glBindTexture(GL_TEXTURE_2D, GpTexture_0);
   glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, WINDOW_WIDTH, WINDOW_HEIGHT, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
   glGenTextures(1, &GpTexture_1);
   glBindTexture(GL_TEXTURE_2D, GpTexture_1);
   glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, WINDOW_WIDTH, WINDOW_HEIGHT, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
   glGenTextures(1, &GpTexture_2);
   glBindTexture(GL_TEXTURE_2D, GpTexture_2);
   glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, WINDOW_WIDTH, WINDOW_HEIGHT, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

   // Create and bind render buffer, and create a 16-bit depth buffer
   glGenRenderbuffers(1, &GdepthRenderbuffer);
   glBindRenderbuffer(GL_RENDERBUFFER, GdepthRenderbuffer);
   glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, WINDOW_WIDTH, WINDOW_HEIGHT);

   // Load Shaders
   vertexShader = LoadShaderFromFile(GL_VERTEX_SHADER, "../vertexShader1.vert" );
   fragmentShader = LoadShaderFromFile(GL_FRAGMENT_SHADER, "../fragmentShader1.frag" );

   // Create the program object
   programObject = glCreateProgram ( );
   
   if ( programObject == 0 )
      return 0;

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

   // (Send from CPU to GPU)
   // Bind vPosition to attribute 0
   glBindAttribLocation(programObject, 0, "vPosition");
   // Bind vColor to attribute 1   
   glBindAttribLocation(programObject, 1, "vColor");
   // Bind vPosition to attribute 2
   glBindAttribLocation(programObject, 2, "vTexCoord");

   // 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 );
		 char infoLog[512];
         glGetProgramInfoLog ( programObject, infoLen, NULL, infoLog );
         printf ( "Error linking program:\n%s\n", infoLog );            
         
         //free ( infoLog );
      }

      glDeleteProgram ( programObject );
      return 0;
   }

   // Store the program object
   GprogramID = programObject;

   glClearColor ( 0.0f, 0.0f, 0.0f, 0.0f );

   // Enable depth test
   glEnable(GL_DEPTH_TEST);

   glEnable(GL_BLEND);
   glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

   //Initialize Matrices
   gPerspectiveMatrix = Matrix4::perspective
   (
	   60.0f,
	   (float)WINDOW_WIDTH / (float)WINDOW_HEIGHT,
	   0.1f, 30.0f
   );

   gViewMatrix = Matrix4::translate(Vector3(0.0f, 0.0f, -2.0f));

   return 1;
}
Esempio n. 29
0
bool Game::init() {
	// init sdl

	SDL_Init(SDL_INIT_EVERYTHING);
	//	SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
	//	SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);

	screen = SDL_SetVideoMode(screen_w, screen_h, screen_depth,
			SDL_HWSURFACE | SDL_DOUBLEBUF | SDL_OPENGL | SDL_FULLSCREEN);
	if (!screen) {
		fprintf(stderr, "Couldn't set GL video mode: %s\n", SDL_GetError());
		SDL_Quit();
		exit(2);
	}
	//SDL_ShowCursor(SDL_DISABLE);

	// init image library
	FreeImage_Initialise();

	SDL_WM_SetCaption("OpenSoldat", NULL);
	glDisable(GL_DEPTH_TEST);
	glewExperimental = GL_TRUE;
	glewInit();
	glEnable(GL_BLEND);
	glEnable(GL_TEXTURE_2D);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

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

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

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

	reshape(screen->w, screen->h);

	//create world
	b2Vec2 gravity(0.0f, -15.0f);
	world = new b2World(gravity);

	//init map
	map = new Map(shaderProgram);
	char mapname[] = "maps/ZS_JungleRumble.PMS";
	std::cout << map->getMapDir() << std::endl;
	map->load(mapname);
	map->addToWorld(world);

	//init animations
//	anims = new animations();
//	anims->loadAnimations();

	//add players
	players = new std::vector<Player*>();
	std::string name = "Rambo";
	std::vector<tagPMS_SPAWNPOINT> spawnPoints = map->getSpawnPoints();
	player = new Player(name, 0, 0, this);
	player->setSpawnPoint(spawnPoints[1]);
	player->addToWorld();

//	std::string name3 = "Rambo";
//	Player *p2 = new Player(name3, world, 0, 0);
//	p2->setSpawnPoint(spawnPoints[3]);
//	p2->addToWorld();

	//init bullets
	bullets = new std::vector<Bullet*>();

	//active player
	//Player *ap = player;

	GLint status;
	glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &status);
	char buffer[512];
	glGetShaderInfoLog(vertexShader, 512, NULL, buffer);
	std::cout << buffer << std::endl;
	viewTrans = glGetUniformLocation(shaderProgram, "view");

	return true;
}
Esempio n. 30
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;
}