示例#1
0
void Box::initTopBottomBack(){

	GLuint VBO;
	GLuint CBO;
	GLuint IBO;

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

	vec3 v0 = vec3(-width/2, width/2, width/2);
	vec3 v1 = vec3(width/2, width/2, width/2);
	vec3 v2 = vec3(-width/2, -width/2, width/2);
	vec3 v3 = vec3(width/2, -width/2, width/2);
	
	vec3 v4 = vec3(-width/2, width/2, -width/2);
	vec3 v5 = vec3(width/2, width/2, -width/2);
	vec3 v6 = vec3(-width/2, -width/2, -width/2);
	vec3 v7 = vec3(width/2, -width/2, -width/2);

	vector<pntVertexData> v;

	vec2 t0 = vec2(0,1);
	vec2 t1 = vec2(1,1);
	vec2 t2 = vec2(0,0);
	vec2 t3 = vec2(1,0);

	vec2 t6 = vec2(0,1);
	vec2 t7 = vec2(1,1);
	vec2 t4 = vec2(0,0);
	vec2 t5 = vec2(1,0);

	v.push_back(pntVertexData(v0, normalize(vec3(-1,1,1)), t0));
	v.push_back(pntVertexData(v1, normalize(vec3(1,1,1)), t1));
	v.push_back(pntVertexData(v2, normalize(vec3(-1,-1,1)), t2));
	v.push_back(pntVertexData(v3, normalize(vec3(1,-1,1)), t3));
	
	v.push_back(pntVertexData(v4, normalize(vec3(-1,1,-1)), t4));
	v.push_back(pntVertexData(v5, normalize(vec3(1,1,-1)), t5));
	v.push_back(pntVertexData(v6, normalize(vec3(-1,-1,-1)), t6));
	v.push_back(pntVertexData(v7, normalize(vec3(1,-1,-1)), t7));

	/*
	glGenBuffers(1, &VBO);
	glBindBuffer(GL_ARRAY_BUFFER, VBO);
	glBufferData(GL_ARRAY_BUFFER, v.size() * sizeof(vec3), &v[0], GL_STATIC_DRAW);
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
	glEnableVertexAttribArray(0);
	*/
	vector<vec4> c;

	vec4 c1 = vec4(1.0f, 0.0f, 0.0f, 1.0f);
	vec4 c2 = vec4(0.0f, 1.0f, 0.0f, 1.0f);
	vec4 c3 = vec4(0.0f, 0.0f, 1.0f, 1.0f);
	vec4 c4 = vec4(1.0f, 1.0f, 0.0f, 1.0f);
	vec4 c5 = vec4(1.0f, 0.0f, 1.0f, 1.0f);

	c.push_back(c1);
	c.push_back(c2);
	c.push_back(c3);
	c.push_back(c4);
	c.push_back(c5);
	c.push_back(c1);
	c.push_back(c2);
	c.push_back(c3);
	/*
	glGenBuffers(1, &CBO);
	glBindBuffer(GL_ARRAY_BUFFER, CBO);
	glBufferData(GL_ARRAY_BUFFER, c.size() * sizeof(vec4), &c[0], GL_STATIC_DRAW);
	glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, 0, 0);
	glEnableVertexAttribArray(2);
	*/
	vector<GLuint> indices;

	// front
	indices.push_back(0);
	indices.push_back(2);
	indices.push_back(1);

	indices.push_back(1);
	indices.push_back(2);
	indices.push_back(3);

	// back
	indices.push_back(6);
	indices.push_back(4);
	indices.push_back(5);

	indices.push_back(5);
	indices.push_back(7);
	indices.push_back(6);

	// top
	indices.push_back(1);
	indices.push_back(5);
	indices.push_back(0);

	indices.push_back(0);
	indices.push_back(5);
	indices.push_back(4);

	// bottom
	indices.push_back(7);
	indices.push_back(3);
	indices.push_back(6);

	indices.push_back(6);
	indices.push_back(3);
	indices.push_back(2);

	numberOfIndices = indices.size();

	/*
	glGenBuffers(1, &IBO);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO);
	glBufferData( GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(GLuint), &indices[0], GL_STATIC_DRAW);
	*/

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

	// finally, create the buffer to hold interleaved  and bind the data to them
	glGenBuffers(1, &VBO);
	glBindBuffer(GL_ARRAY_BUFFER, VBO); // Buffer for vertex data
	glBufferData(GL_ARRAY_BUFFER, v.size() * sizeof(pntVertexData), &v[0], GL_STATIC_DRAW); //Buffering vertex data

	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(pntVertexData), 0);
	glEnableVertexAttribArray(0);

	glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(pntVertexData), (const GLvoid*)sizeof(vec3) );
	glEnableVertexAttribArray(1);

	glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE,  sizeof(pntVertexData),  (const GLvoid*)(2 * sizeof(vec3)) );
	glEnableVertexAttribArray(3);

	// Generate a buffer for the indices
	glGenBuffers(1, &IBO);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), &indices[0] , GL_STATIC_DRAW);
} // end initialize
示例#2
0
/**
 * Function for initialization.
 */
GLUSboolean init(GLUSvoid)
{
	// Points of a cube.
	GLfloat
			points[] =
					{ -0.5f, -0.5f, -0.5f, 1.0f, -0.5f, -0.5f, +0.5f, 1.0f, +0.5f, -0.5f, +0.5f, 1.0f, +0.5f, -0.5f, -0.5f, 1.0f, -0.5f, +0.5f, -0.5f, 1.0f, -0.5f, +0.5f, +0.5f, 1.0f, +0.5f, +0.5f, +0.5f, 1.0f, +0.5f, +0.5f, -0.5f, 1.0f, -0.5f, -0.5f, -0.5f, 1.0f, -0.5f, +0.5f, -0.5f, 1.0f, +0.5f, +0.5f, -0.5f, 1.0f, +0.5f, -0.5f, -0.5f, 1.0f, -0.5f, -0.5f, +0.5f, 1.0f, -0.5f, +0.5f, +0.5f, 1.0f, +0.5f, +0.5f, +0.5f, 1.0f, +0.5f, -0.5f, +0.5f, 1.0f, -0.5f, -0.5f, -0.5f, 1.0f, -0.5f, -0.5f, +0.5f, 1.0f, -0.5f, +0.5f, +0.5f, 1.0f, -0.5f, +0.5f, -0.5f, 1.0f, +0.5f, -0.5f, -0.5f, 1.0f, +0.5f, -0.5f, +0.5f, 1.0f, +0.5f, +0.5f, +0.5f, 1.0f, +0.5f, +0.5f, -0.5f, 1.0f };

	// Normals of a cube.
	GLfloat
			normals[] =
					{ +0.0f, -1.0f, +0.0f, +0.0f, -1.0f, +0.0f, +0.0f, -1.0f, +0.0f, +0.0f, -1.0f, +0.0f, +0.0f, +1.0f, +0.0f, +0.0f, +1.0f, +0.0f, +0.0f, +1.0f, +0.0f, +0.0f, +1.0f, +0.0f, +0.0f, +0.0f, -1.0f, +0.0f, +0.0f, -1.0f, +0.0f, +0.0f, -1.0f, +0.0f, +0.0f, -1.0f, +0.0f, +0.0f, +1.0f, +0.0f, +0.0f, +1.0f, +0.0f, +0.0f, +1.0f, +0.0f, +0.0f, +1.0f, -1.0f, +0.0f, +0.0f, -1.0f, +0.0f, +0.0f, -1.0f, +0.0f, +0.0f, -1.0f, +0.0f, +0.0f, +1.0f, +0.0f, +0.0f, +1.0f, +0.0f, +0.0f, +1.0f, +0.0f, +0.0f, +1.0f, +0.0f, +0.0f };

	// The associated indices.
	GLuint indices[] = { 0, 2, 1, 0, 3, 2, 4, 5, 6, 4, 6, 7, 8, 9, 10, 8, 10, 11, 12, 15, 14, 12, 14, 13, 16, 17, 18, 16, 18, 19, 20, 23, 22, 20, 22, 21 };

	GLUStgaimage image;

	GLUStextfile vertexSource;

	GLUStextfile fragmentSource;

	// Load the source of the vertex shader.
	glusLoadTextFile("../src/Example07/Vertex.vs", &vertexSource);

	// Load the source of the fragment shader.
	glusLoadTextFile("../src/Example07/Fragment.fs", &fragmentSource);

	// Build and ...
	glusBuildProgram(&g_program, (const GLUSchar**) &vertexSource.text, 0, 0, 0, (const GLUSchar**) &fragmentSource.text);

	// Destroy the text resource
	glusDestroyTextFile(&vertexSource);

	// Destroy the text resource
	glusDestroyTextFile(&fragmentSource);

	// ToDo:
	glGenVertexArrays(1, &g_vao);

	// ToDo:
	glBindVertexArray(g_vao);

	// http://www.opengl.org/sdk/docs/man/xhtml/glGetUniformLocation.xml
	g_projectionLocation = glGetUniformLocation(g_program.program, "projectionMatrix");

	// http://www.opengl.org/sdk/docs/man/xhtml/glGetUniformLocation.xml
	g_modelViewLocation = glGetUniformLocation(g_program.program, "modelViewMatrix");

	// http://www.opengl.org/sdk/docs/man/xhtml/glGetUniformLocation.xml
	g_inverseCameraLocation = glGetUniformLocation(g_program.program, "inverseCameraMatrix");

	// http://www.opengl.org/sdk/docs/man/xhtml/glGetUniformLocation.xml
	g_cubemapLocation = glGetUniformLocation(g_program.program, "cubemap");

	// http://www.opengl.org/sdk/docs/man/xhtml/glGetAttribLocation.xml
	g_vertexLocation = glGetAttribLocation(g_program.program, "vertex");

	// http://www.opengl.org/sdk/docs/man/xhtml/glGetAttribLocation.xml
	g_normalLocation = glGetAttribLocation(g_program.program, "normal");

	// http://www.opengl.org/sdk/docs/man/xhtml/glGenBuffers.xml
	glGenBuffers(1, &g_vertices);

	// http://www.opengl.org/sdk/docs/man/xhtml/glBindBuffer.xml
	glBindBuffer(GL_ARRAY_BUFFER, g_vertices);

	// http://www.opengl.org/sdk/docs/man/xhtml/glBufferData.xml
	glBufferData(GL_ARRAY_BUFFER, 24 * 4 * sizeof(GLfloat), (GLfloat*) points, GL_STATIC_DRAW);

	// http://www.opengl.org/sdk/docs/man/xhtml/glGenBuffers.xml
	glGenBuffers(1, &g_normals);

	// http://www.opengl.org/sdk/docs/man/xhtml/glBindBuffer.xml
	glBindBuffer(GL_ARRAY_BUFFER, g_normals);

	// http://www.opengl.org/sdk/docs/man/xhtml/glBufferData.xml
	glBufferData(GL_ARRAY_BUFFER, 24 * 3 * sizeof(GLfloat), (GLfloat*) normals, GL_STATIC_DRAW);

	// http://www.opengl.org/sdk/docs/man/xhtml/glGenBuffers.xml
	glGenBuffers(1, &g_indices);

	// http://www.opengl.org/sdk/docs/man/xhtml/glBindBuffer.xml
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_indices);

	// http://www.opengl.org/sdk/docs/man/xhtml/glBufferData.xml
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, 6 * 2 * 3 * sizeof(GLuint), (GLuint*) indices, GL_STATIC_DRAW);

	// http://www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/gentextures.html
	glGenTextures(1, &g_cubemap);

	// http://www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/bindtexture.html
	glBindTexture(GL_TEXTURE_CUBE_MAP, g_cubemap);

	glusLoadTgaImage("cm_left.tga", &image);
	// http://www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/teximage2d.html
	glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0, image.format, image.width, image.height, 0, image.format, GL_UNSIGNED_BYTE, image.data);
	glusDestroyTgaImage(&image);

	glusLoadTgaImage("cm_right.tga", &image);
	// http://www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/teximage2d.html
	glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_X, 0, image.format, image.width, image.height, 0, image.format, GL_UNSIGNED_BYTE, image.data);
	glusDestroyTgaImage(&image);

	glusLoadTgaImage("cm_top.tga", &image);
	// http://www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/teximage2d.html
	glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Y, 0, image.format, image.width, image.height, 0, image.format, GL_UNSIGNED_BYTE, image.data);
	glusDestroyTgaImage(&image);

	glusLoadTgaImage("cm_bottom.tga", &image);
	// http://www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/teximage2d.html
	glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, 0, image.format, image.width, image.height, 0, image.format, GL_UNSIGNED_BYTE, image.data);
	glusDestroyTgaImage(&image);

	glusLoadTgaImage("cm_back.tga", &image);
	// http://www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/teximage2d.html
	glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Z, 0, image.format, image.width, image.height, 0, image.format, GL_UNSIGNED_BYTE, image.data);
	glusDestroyTgaImage(&image);

	glusLoadTgaImage("cm_front.tga", &image);
	// http://www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/teximage2d.html
	glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, 0, image.format, image.width, image.height, 0, image.format, GL_UNSIGNED_BYTE, image.data);
	glusDestroyTgaImage(&image);

	// http://www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/texparameter.html
	glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

	// http://www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/texparameter.html
	glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

	// http://www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/texparameter.html
	glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_REPEAT);

	// http://www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/texparameter.html
	glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_REPEAT);

	// http://www.opengl.org/sdk/docs/man/xhtml/glUseProgram.xml
	glUseProgram(g_program.program);

	// http://www.opengl.org/sdk/docs/man/xhtml/glBindBuffer.xml
	glBindBuffer(GL_ARRAY_BUFFER, g_vertices);

	// http://www.opengl.org/sdk/docs/man/xhtml/glVertexAttribPointer.xml
	glVertexAttribPointer(g_vertexLocation, 4, GL_FLOAT, GL_FALSE, 0, 0);

	// http://www.opengl.org/sdk/docs/man/xhtml/glEnableVertexAttribArray.xml
	glEnableVertexAttribArray(g_vertexLocation);

	// http://www.opengl.org/sdk/docs/man/xhtml/glBindBuffer.xml
	glBindBuffer(GL_ARRAY_BUFFER, g_normals);

	// http://www.opengl.org/sdk/docs/man/xhtml/glVertexAttribPointer.xml
	glVertexAttribPointer(g_normalLocation, 3, GL_FLOAT, GL_FALSE, 0, 0);

	// http://www.opengl.org/sdk/docs/man/xhtml/glEnableVertexAttribArray.xml
	glEnableVertexAttribArray(g_normalLocation);

	// http://www.opengl.org/sdk/docs/man/xhtml/glUniform.xml
	glUniform1i(g_cubemapLocation, 0);

	// http://www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/clearcolor.html
	glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

	// http://www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/cleardepth.html
	glClearDepth(1.0f);

	//http://www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/enable.html
	glEnable( GL_DEPTH_TEST);

	//http://www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/enable.html
	glEnable( GL_CULL_FACE);

	return GLUS_TRUE;
}
示例#3
0
// The MAIN function, from here we start the application and run the game loop
int main()
{
	std::cout << "Starting GLFW context, OpenGL 3.1" << std::endl;
	// Init GLFW
	glfwInit();
	// Set all the required options for GLFW
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); // only supports 3.1 on intel hd 3000
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // requires 3.3+ for this line to work
	glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); // asks if the window should be resized by the user
	//glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // for mac

	// Create a GLFWwindow object that we can use for GLFW's functions
	GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr); // creates a window, or returns nullptr if error
	if (window == nullptr)
	{
		std::cout << "Failed to create GLFW window 3.3" << std::endl;
		std::cout << "Starting to create GLFW window 3.1" << std::endl;
		glfwTerminate();
		glfwInit();
		glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
		glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1); // only supports 3.1 on intel hd 3000
		glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
		window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr);
		GLVer = 3.1;

		if (window == nullptr)
		{
			std::cout << "Failed to create GLFW window 3.1" << std::endl;
			std::cout << "Starting to create GLFW window 2.1" << std::endl;
			glfwTerminate();
			glfwInit();
			glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
			glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1); 
			glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
			window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr);
			GLVer = 2.1;

			if (window == nullptr)
			{
				std::cout << "Failed to create GLFW window 2.1" << std::endl;
				glfwTerminate();
				return -1;
			}
		}
	}
	glfwMakeContextCurrent(window); // makes the window the main context for draw operations
	// Set the required callback functions
	glfwSetKeyCallback(window, key_callback);
	//glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
	glfwSetCursorPosCallback(window, mouse_callback);
	glfwSetScrollCallback(window, scroll_callback);

	// Set this to true so GLEW knows to use a modern approach to retrieving function pointers and extensions
	glewExperimental = GL_TRUE; // use modern techniques for managine opengl functionality, mostly for 3.3+
	// Initialize GLEW to setup the OpenGL Function pointers
	if (glewInit() != GLEW_OK)
	{
		std::cout << "Failed to initialize GLEW" << std::endl;
		return -1;
	}

	// Define the viewport dimensions
	int width, height;
	glfwGetFramebufferSize(window, &width, &height); // gets size of screen
	glViewport(0, 0, width, height); 

	//Shader testShader("lighting.vert", "lighting.frag");
	Shader lightingShader("lighting.vert", "lighting.frag");
	Shader lampShader("lamp.vert", "lamp.frag");

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

		-0.5f, -0.5f,  0.5f,  0.0f,  0.0f, 1.0f,
		0.5f, -0.5f,  0.5f,  0.0f,  0.0f, 1.0f,
		0.5f,  0.5f,  0.5f,  0.0f,  0.0f, 1.0f,
		0.5f,  0.5f,  0.5f,  0.0f,  0.0f, 1.0f,
		-0.5f,  0.5f,  0.5f,  0.0f,  0.0f, 1.0f,
		-0.5f, -0.5f,  0.5f,  0.0f,  0.0f, 1.0f,

		-0.5f,  0.5f,  0.5f, -1.0f,  0.0f,  0.0f,
		-0.5f,  0.5f, -0.5f, -1.0f,  0.0f,  0.0f,
		-0.5f, -0.5f, -0.5f, -1.0f,  0.0f,  0.0f,
		-0.5f, -0.5f, -0.5f, -1.0f,  0.0f,  0.0f,
		-0.5f, -0.5f,  0.5f, -1.0f,  0.0f,  0.0f,
		-0.5f,  0.5f,  0.5f, -1.0f,  0.0f,  0.0f,

		0.5f,  0.5f,  0.5f,  1.0f,  0.0f,  0.0f,
		0.5f,  0.5f, -0.5f,  1.0f,  0.0f,  0.0f,
		0.5f, -0.5f, -0.5f,  1.0f,  0.0f,  0.0f,
		0.5f, -0.5f, -0.5f,  1.0f,  0.0f,  0.0f,
		0.5f, -0.5f,  0.5f,  1.0f,  0.0f,  0.0f,
		0.5f,  0.5f,  0.5f,  1.0f,  0.0f,  0.0f,

		-0.5f, -0.5f, -0.5f,  0.0f, -1.0f,  0.0f,
		0.5f, -0.5f, -0.5f,  0.0f, -1.0f,  0.0f,
		0.5f, -0.5f,  0.5f,  0.0f, -1.0f,  0.0f,
		0.5f, -0.5f,  0.5f,  0.0f, -1.0f,  0.0f,
		-0.5f, -0.5f,  0.5f,  0.0f, -1.0f,  0.0f,
		-0.5f, -0.5f, -0.5f,  0.0f, -1.0f,  0.0f,

		-0.5f,  0.5f, -0.5f,  0.0f,  1.0f,  0.0f,
		0.5f,  0.5f, -0.5f,  0.0f,  1.0f,  0.0f,
		0.5f,  0.5f,  0.5f,  0.0f,  1.0f,  0.0f,
		0.5f,  0.5f,  0.5f,  0.0f,  1.0f,  0.0f,
		-0.5f,  0.5f,  0.5f,  0.0f,  1.0f,  0.0f,
		-0.5f,  0.5f, -0.5f,  0.0f,  1.0f,  0.0f
	};



	GLint indices[] = {
		0,1,3,
		1,2,3
	};


	GLuint VBO; // vertex buffer object
	glGenBuffers(1, &VBO); // generate buffer ID
	GLuint VAO;
	glGenVertexArrays(1, &VAO);
	GLuint EBO; // element buffer object to avoid storing repeated vertices
	glGenBuffers(1, &EBO);

	GLuint lightingVAO;
	glGenVertexArrays(1, &lightingVAO);


	// can initialise more than one at a time using GLuint VAOs[2] and glGenVertexArrays(2,VAOs)
	//GLuint VAO2;
	//glGenVertexArrays(1, &VAO2);

	// initialisation code
	// 1: bind vertex array object
	//glBindVertexArray(VAO);
	//glBindVertexArray(lightingVAO);
	glBindVertexArray(VAO);
	// 2: copy vertices array in buffer for opengl


	glBindBuffer(GL_ARRAY_BUFFER, VBO);
	glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
	// 2.5: copy index array in elemennt buffer
	//glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
	//glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
		// GL_STATIC_DRAW = data that is unlikely to change
		// GL_DYNAMIC_DRAW = data that is likely to change a lot
		// GL_STREAM_DRAW = data will change every time it is drawn


	// 3: set vertex position attributes pointers
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)0);
	glEnableVertexAttribArray(0);
	// 3.5: set vertex normal attribute pointers
	glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
	glEnableVertexAttribArray(1);
	// 4: unbind VAO (NOT the EBO)
	glBindVertexArray(0);

	// bind other vao
	glBindVertexArray(lightingVAO);
	glBindBuffer(GL_ARRAY_BUFFER, VBO);
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)0);
	glEnableVertexAttribArray(0);
	glBindVertexArray(0);



	


	// load texture
	
	// matrix goodness!

	
	glEnable(GL_DEPTH_TEST); // required for z-buffer to work


	// Game loop
	while (!glfwWindowShouldClose(window))
	{
		// Check if any events have been activiated (key pressed, mouse moved etc.) and call corresponding response functions
		glfwPollEvents();
		// time update
		currentFrame = glfwGetTime();
		deltaTime = currentFrame - lastFrame;
		lastFrame = currentFrame;





		movement();
		// Render
	

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

		lightingShader.use();
		GLuint objectColorLoc = glGetUniformLocation(lightingShader.program, "objectColor");
		GLuint lightColorLoc = glGetUniformLocation(lightingShader.program, "lightColor");

		glUniform3f(objectColorLoc, 1.0f, 0.5f, 0.31f);
		glUniform3f(lightColorLoc, 1.0f, 1.0f, 1.0f);



		// matrix
		glm::mat4 model;
		model = glm::mat4();
		
		//model = glm::translate(model, lightPos);
		//model = glm::scale(model, glm::vec3(0.2f));
		glUniformMatrix4fv(glGetUniformLocation(lightingShader.program, "model"), 1, GL_FALSE, glm::value_ptr(model));

		glm::mat4 view;
		view = camera.GetViewMatrix();
		glUniformMatrix4fv(glGetUniformLocation(lightingShader.program, "view"), 1, GL_FALSE, glm::value_ptr(view));

		glm::mat4 projection;
		projection = glm::perspective(glm::radians(camera.zoom), (GLfloat)WIDTH/(GLfloat)HEIGHT, 0.1f, 100.0f);
		glUniformMatrix4fv(glGetUniformLocation(lightingShader.program, "projection"), 1, GL_FALSE, glm::value_ptr(projection));
		
		glUniform3f(glGetUniformLocation(lightingShader.program, "lightPos"), lightPos.x, lightPos.y, lightPos.z);
		glUniform3f(glGetUniformLocation(lightingShader.program, "viewPos"), camera.position.x, camera.position.y, camera.position.z);

		// draw triangle
		glBindVertexArray(VAO);

		glDrawArrays(GL_TRIANGLES, 0, 36);



		lampShader.use();
		// change lamp position
		lightPos = glm::vec3(sin(glfwGetTime()*glm::radians(45.0f)), 1.0f, cos(glfwGetTime()*glm::radians(45.0f)));
		model = glm::mat4();
		model = glm::translate(model, lightPos);
		model = glm::scale(model, glm::vec3(0.2f)); // Make it a smaller cube
		glUniformMatrix4fv(glGetUniformLocation(lampShader.program, "model"), 1, GL_FALSE, glm::value_ptr(model));
		glUniformMatrix4fv(glGetUniformLocation(lampShader.program, "view"), 1, GL_FALSE, glm::value_ptr(view));
		glUniformMatrix4fv(glGetUniformLocation(lampShader.program, "projection"), 1, GL_FALSE, glm::value_ptr(projection));
		glBindVertexArray(lightingVAO);
		glDrawArrays(GL_TRIANGLES, 0, 36);
		glBindVertexArray(0);




		glBindVertexArray(0);



		//glDrawArrays(GL_TRIANGLES, 0, 3);
		//glDrawElements(GL_TRIANGLES, 9, GL_UNSIGNED_INT, 0);
		//glUseProgram(shaderProgram2);
		//glBindVertexArray(VAO2);
		//glDrawArrays(GL_TRIANGLES, 0, 3);
		//glBindVertexArray(0);

		


		// Swap the screen buffers
		glfwSwapBuffers(window);
	}
	glDeleteVertexArrays(1, &VAO);
	glDeleteBuffers(1, &VBO);
	glDeleteBuffers(1, &EBO);
	// Terminate GLFW, clearing any resources allocated by GLFW.
	glfwTerminate();
	return 0;
}
示例#4
0
文件: gl.cpp 项目: ZeXx86/gen
void gl_render_terrain (terrain_t *t, camera_t *c)
{
//#define FRUSTUM 1
#ifdef FRUSTUM
	if (frustum_check (t, c) == false)
		return;
#endif
	if (t->state & TERRAIN_STATE_UPDATE)
		vbo_free (&t->vbo_id);
	
	if (!t->vbo_id)
		t->vbo_id = vbo_alloc (t->gl_buf, t->gl_buf_len * sizeof (float) * 9);
	
	glBindBuffer (GL_ARRAY_BUFFER, t->vbo_id);
	
	/* Vykreslovani terenu */
	glm::mat4 mdl_matrix;
	
	mdl_matrix = glm::translate (glm::vec3 (t->origin_x-TERRAIN_DIM, t->origin_z, t->origin_y-TERRAIN_DIM));

	/* enable program and set uniform variables */
	glUseProgram (shader[0]);
			
	glm::mat4 tmp = c->view * mdl_matrix;

	int uniform = glGetUniformLocation (shader[0], "PMatrix");
	glUniformMatrix4fv (uniform, 1, GL_FALSE, (float*)&c->projection[0]);
	uniform = glGetUniformLocation (shader[0], "VMatrix");
	glUniformMatrix4fv (uniform, 1, GL_FALSE, (float*)&c->view[0]);
	uniform = glGetUniformLocation (shader[0], "MVMatrix");
	glUniformMatrix4fv (uniform, 1, GL_FALSE, (float*)&tmp[0]);
	uniform = glGetUniformLocation (shader[0], "NormalMatrix");
	glUniformMatrix3fv (uniform, 1, GL_FALSE, (float*)&(glm::inverseTranspose(glm::mat3(tmp)))[0]);
			
	shader_getuniform_light (shader[0], &light[0]);
	shader_getuniform_material (shader[0], &mat[0]);
				
	GLuint tex_id  = glGetUniformLocation (shader[0], "tex_sampler0");
	glUniform1i (tex_id, 0);
	tex_id  = glGetUniformLocation (shader[0], "tex_sampler1");
	glUniform1i (tex_id, 1);
	tex_id  = glGetUniformLocation (shader[0], "tex_sampler2");
	glUniform1i (tex_id, 2);

	/* texura */
	glActiveTexture (GL_TEXTURE2); 
	glBindTexture (GL_TEXTURE_2D, tex_get (4));
	
	glActiveTexture (GL_TEXTURE1); 
	glBindTexture (GL_TEXTURE_2D, tex_get (3));
			
	glActiveTexture (GL_TEXTURE0); 
	glBindTexture (GL_TEXTURE_2D, tex_get (2));


	glEnableVertexAttribArray (0);
	glEnableVertexAttribArray (1);
	glEnableVertexAttribArray (2);
	glEnableVertexAttribArray (3);
	
	glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, (9 * sizeof(GLfloat)), 0);
	glVertexAttribPointer (1, 3, GL_FLOAT, GL_FALSE, (9 * sizeof(GLfloat)), (GLvoid *) (3 * sizeof(GLfloat)));
	glVertexAttribPointer (2, 2, GL_FLOAT, GL_FALSE, (9 * sizeof(GLfloat)), (GLvoid *) (6 * sizeof(GLfloat)));
	glVertexAttribPointer (3, 1, GL_FLOAT, GL_FALSE, (9 * sizeof(GLfloat)), (GLvoid *) (8 * sizeof(GLfloat)));
	
	/* k vykresleni pouzivame Vertex Buffer Object */
	glDrawArrays (GL_TRIANGLES, 0, t->gl_buf_len);
	
	glDisableVertexAttribArray (0);
	glDisableVertexAttribArray (1);
	glDisableVertexAttribArray (2);
	glDisableVertexAttribArray (3);
	
	glBindBuffer (GL_ARRAY_BUFFER, 0);
	
	/* vypneme shader */
	glUseProgram (0);
}
示例#5
0
// called by the Qt GUI system, to allow OpenGL drawing commands
void Renderer::paintGL()
{
    // Clear the screen buffers

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glEnable(GL_DEPTH_TEST);

    glPolygonMode(GL_FRONT_AND_BACK, polygonMode);

    // Set the current shader program

    glUseProgram(m_programID);

    // Modify the current projection matrix so that we move the
    // camera away from the origin.  We'll draw the game at the
    // origin, and we need to back up to see it.

    QMatrix4x4 view_matrix;
    view_matrix.translate(0.0f, 0.0f, -40.0f);

    view_matrix = view_matrix * scalingMatrix;  //Scaling matrix is either the identity or a composite of previous and current scaling transformation
    view_matrix = view_matrix * roataionMatrix; //rotation matrix is either the identity or a composite of previous and current rotataion


    glUniformMatrix4fv(m_VMatrixUniform, 1, false, view_matrix.data());

    // Not implemented: set up lighting (if necessary)

    // Not implemented: scale and rotate the scene

    QMatrix4x4 model_matrix;

    // You'll be drawing unit cubes, so the game will have width
    // 10 and height 24 (game = 20, stripe = 4).  Let's translate
    // the game so that we can draw it starting at (0,0) but have
    // it appear centered in the window.

    model_matrix.translate(-5.0f, -12.0f, 0.0f);
    // Not implemented: actually draw the current game state.
    // Here's some test code that draws red triangles at the
    // corners of the game board.
    // draw border

    // Change the color of the border
    changeCubeColor(7);
    if (cube.CubeVertices().size() > 0)
    {
        glEnableVertexAttribArray(m_posAttr);
        glEnableVertexAttribArray(m_colAttr);
        glEnableVertexAttribArray(m_norAttr);

        QMatrix4x4 boxMatrix(model_matrix);
        // translated back once along the x axis since we start with a translation
        boxMatrix.translate(-2.0, 0.0, 0.0);
        for (int i = 0; i < 12; i++)
        {
            boxMatrix.translate(1.0, 0.0, 0.0);
            glUniformMatrix4fv(m_MMatrixUniform, 1, false, boxMatrix.data());
            glDrawArrays(GL_QUADS, 0, cube.CubeVertices().size()/3); // 3 coordinates per vertex
        }

        for (int i = 0; i < 24; i++)
        {
            boxMatrix.translate(0.0, 1.0, 0.0);
            glUniformMatrix4fv(m_MMatrixUniform, 1, false, boxMatrix.data());
            glDrawArrays(GL_QUADS, 0, cube.CubeVertices().size()/3); // 3 coordinates per vertex
        }

        // Reset back to the bottom left corner (reversing from the previous two loops
        boxMatrix.translate(-11.0, -24.0, 0.0);
        for (int i = 0; i < 24; i++)
        {
            boxMatrix.translate(0.0, 1.0, 0.0);
            glUniformMatrix4fv(m_MMatrixUniform, 1, false, boxMatrix.data());
            glDrawArrays(GL_QUADS, 0, cube.CubeVertices().size()/3); // 3 coordinates per vertex
        }

        //reset the model back to 0,0,0
        boxMatrix.translate(0.0, -24.0, 0.0);

        // transelate one step in x and y to avoid border overlap
        boxMatrix.translate(1.0, 1.0, 0.0);

        for (int i = 0; i<24; i++)
        {
            for (int j = 0; j<10; j++)
            {
                // doing drawing on m_gameBoard which is copy of border_ from the game object
                // instead of using m_game->get(r,c), m_gameBoard needs to be used for network feature to work properly
                if (!m_gameBoard.empty() && m_gameBoard[j + 10 *i] != -1)
                {
                    // Check in which mode should the cube colors be
                    if(isMulticolored)
                    {
                        setMultipleColors(m_gameBoard[j + 10 *i]);
                    }
                    else
                    {
                        changeCubeColor(m_gameBoard[j + 10 *i]);
                    }
                    // draw the box in it's correct position
                    boxMatrix.translate((float)j, (float)i, 0.0);
                    glUniformMatrix4fv(m_MMatrixUniform, 1, false, boxMatrix.data());
                    glDrawArrays(GL_QUADS, 0, cube.CubeVertices().size()/3); // 3 coordinates per vertex
                    // reset back to 0, 0 so next box gets drawn properly
                    boxMatrix.translate((float)-j, (float)-i, 0.0);
                }
            }
        }

        glDisableVertexAttribArray(m_norAttr);
        glDisableVertexAttribArray(m_colAttr);
        glDisableVertexAttribArray(m_posAttr);
    }

    // deactivate the program
    m_program->release();

}
示例#6
0
void RenderCube()
{
    // Initialize (if necessary)
    if (cubeVAO == 0)
    {
        GLfloat vertices[] = {
            // Back face
            -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, // Bottom-left
            0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, // top-right
            0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, // bottom-right         
            0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f,  // top-right
            -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f,  // bottom-left
            -0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f,// top-left
            // Front face
            -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, // bottom-left
            0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f,  // bottom-right
            0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f,  // top-right
            0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, // top-right
            -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f,  // top-left
            -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,  // bottom-left
            // Left face
            -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, // top-right
            -0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f, // top-left
            -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f,  // bottom-left
            -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, // bottom-left
            -0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f,  // bottom-right
            -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, // top-right
            // Right face
            0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, // top-left
            0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, // bottom-right
            0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, // top-right         
            0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f,  // bottom-right
            0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f,  // top-left
            0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, // bottom-left     
            // Bottom face
            -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, // top-right
            0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 1.0f, // top-left
            0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f,// bottom-left
            0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, // bottom-left
            -0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, // bottom-right
            -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, // top-right
            // Top face
            -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f,// top-left
            0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, // bottom-right
            0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, // top-right     
            0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, // bottom-right
            -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f,// top-left
            -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f // bottom-left        
        };
        glGenVertexArrays(1, &cubeVAO);
        glGenBuffers(1, &cubeVBO);
        // Fill buffer
        glBindBuffer(GL_ARRAY_BUFFER, cubeVBO);
        glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
        // Link vertex attributes
        glBindVertexArray(cubeVAO);
        glEnableVertexAttribArray(0);
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)0);
        glEnableVertexAttribArray(1);
        glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
        glEnableVertexAttribArray(2);
        glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(6 * sizeof(GLfloat)));
        glBindBuffer(GL_ARRAY_BUFFER, 0);
        glBindVertexArray(0);
    }
    // Render Cube
    glBindVertexArray(cubeVAO);
    glDrawArrays(GL_TRIANGLES, 0, 36);
    glBindVertexArray(0);
}
示例#7
0
文件: video.c 项目: ivarb/p1stream
void p1_video_start(P1VideoFull *videof)
{
    P1Video *video = (P1Video *) videof;
    P1Object *videoobj = (P1Object *) videof;
    P1ListNode *head;
    P1ListNode *node;
    cl_int cl_err;
    GLenum gl_err;
    int i_ret;
    bool b_ret;
    size_t size;

    video->width = videof->cfg_width;
    video->height = videof->cfg_height;
    videof->out_size = video->width * video->height * 1.5;
    videof->yuv_work_size[0] = video->width / 2;
    videof->yuv_work_size[1] = video->height / 2;

    b_ret = p1_video_init_platform(videof);
    if (!b_ret)
        goto fail;

    cl_device_id device_id;
    cl_err = clGetContextInfo(videof->cl, CL_CONTEXT_DEVICES, sizeof(cl_device_id), &device_id, &size);
    if (cl_err != CL_SUCCESS || size == 0) {
        p1_log(videoobj, P1_LOG_ERROR, "Failed to get CL device info: OpenCL error %d", cl_err);
        goto fail_platform;
    }

    videof->clq = clCreateCommandQueue(videof->cl, device_id, 0, &cl_err);
    if (cl_err != CL_SUCCESS) {
        p1_log(videoobj, P1_LOG_ERROR, "Failed to create CL command queue: OpenCL error %d", cl_err);
        goto fail_platform;
    }

    i_ret = x264_picture_alloc(&videof->out_pic, X264_CSP_I420, video->width, video->height);
    if (i_ret < 0) {
        p1_log(videoobj, P1_LOG_ERROR, "Failed to alloc x264 picture buffer");
        goto fail_clq;
    }

    glGenVertexArrays(1, &videof->vao);
    glGenBuffers(1, &videof->vbo);
    videof->program = glCreateProgram();
    if ((gl_err = glGetError()) != GL_NO_ERROR) {
        p1_log(videoobj, P1_LOG_ERROR, "Failed to create GL objects: OpenGL error %d", gl_err);
        goto fail_out_pic;
    }

    glBindAttribLocation(videof->program, 0, "a_Position");
    glBindAttribLocation(videof->program, 1, "a_TexCoords");
    glBindFragDataLocation(videof->program, 0, "o_FragColor");
    b_ret = p1_video_build_program(videoobj, videof->program, simple_vertex_shader, simple_fragment_shader);
    if (!b_ret)
        goto fail_out_pic;
    videof->tex_u = glGetUniformLocation(videof->program, "u_Texture");

    videof->tex_mem = clCreateFromGLTexture(videof->cl, CL_MEM_READ_ONLY, GL_TEXTURE_RECTANGLE, 0, videof->tex, &cl_err);
    if (cl_err != CL_SUCCESS) {
        p1_log(videoobj, P1_LOG_ERROR, "Failed to create CL input buffer: OpenCL error %d", cl_err);
        goto fail_out_pic;
    }

    videof->out_mem = clCreateBuffer(videof->cl, CL_MEM_WRITE_ONLY, videof->out_size, NULL, &cl_err);
    if (cl_err != CL_SUCCESS) {
        p1_log(videoobj, P1_LOG_ERROR, "Failed to create CL output buffer: OpenCL error %d", cl_err);
        goto fail_tex_mem;
    }

    cl_program yuv_program = clCreateProgramWithSource(videof->cl, 1, &yuv_kernel_source, NULL, &cl_err);
    if (cl_err != CL_SUCCESS) {
        p1_log(videoobj, P1_LOG_ERROR, "Failed to create CL program: OpenCL error %d", cl_err);
        goto fail_out_mem;
    }
    cl_err = clBuildProgram(yuv_program, 0, NULL, NULL, NULL, NULL);
    if (cl_err != CL_SUCCESS) {
        p1_log(videoobj, P1_LOG_ERROR, "Failed to build CL program: OpenCL error %d", cl_err);
        clReleaseProgram(yuv_program);
        goto fail_out_mem;
    }
    videof->yuv_kernel = clCreateKernel(yuv_program, "yuv", &cl_err);
    clReleaseProgram(yuv_program);
    if (cl_err != CL_SUCCESS) {
        p1_log(videoobj, P1_LOG_ERROR, "Failed to create CL kernel: OpenCL error %d", cl_err);
        goto fail_out_mem;
    }

    // GL state init. Most of this is up here because we can.
    glViewport(0, 0, video->width, video->height);
    glClearColor(0, 0, 0, 1);
    glActiveTexture(GL_TEXTURE0);
    glBindBuffer(GL_ARRAY_BUFFER, videof->vbo);
    glUseProgram(videof->program);
    glUniform1i(videof->tex_u, 0);
    glBindVertexArray(videof->vao);
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, vbo_stride, 0);
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, vbo_stride, vbo_tex_coord_offset);
    glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);
    if ((gl_err = glGetError()) != GL_NO_ERROR) {
        p1_log(videoobj, P1_LOG_ERROR, "Failed to initialize GL state: OpenGL error %d", gl_err);
        goto fail_yuv_kernel;
    }

    cl_err = clSetKernelArg(videof->yuv_kernel, 0, sizeof(cl_mem), &videof->tex_mem);
    if (cl_err != CL_SUCCESS) {
        p1_log(videoobj, P1_LOG_ERROR, "Failed to set CL kernel arg: OpenCL error %d", cl_err);
        goto fail_yuv_kernel;
    }
    cl_err = clSetKernelArg(videof->yuv_kernel, 1, sizeof(cl_mem), &videof->out_mem);
    if (cl_err != CL_SUCCESS) {
        p1_log(videoobj, P1_LOG_ERROR, "Failed to set CL kernel arg: OpenCL error %d", cl_err);
        goto fail_yuv_kernel;
    }

    // Change state.
    videoobj->state.current = P1_STATE_RUNNING;
    p1_object_notify(videoobj);

    // Link already active sources.
    head = &video->sources;
    p1_list_iterate(head, node) {
        P1Source *src = p1_list_get_container(node, P1Source, link);
        P1Object *obj = (P1Object *) src;
        P1VideoSource *vsrc = (P1VideoSource *) src;

        if (obj->state.current == P1_STATE_RUNNING)
            p1_video_link_source(vsrc);
    }
示例#8
0
/*Enables the vertex attribute by location */
GLvoid ShaderProgram::enableVertexAttribute(int location)
{
	checkManaged();
	glEnableVertexAttribArray(location);
}
/*!****************************************************************************
 @Function		DrawMesh
 @Input			i32NodeIndex		Node index of the mesh to draw
 @Description	Draws a SPODMesh after the model view matrix has been set and
				the meterial prepared.
******************************************************************************/
void OGLES3PVRScopeRemote::DrawMesh(int i32NodeIndex)
{
	CPPLProcessingScoped PPLProcessingScoped(m_psSPSCommsData,
		__FUNCTION__, static_cast<unsigned int>(strlen(__FUNCTION__)), m_i32FrameCounter);

	int i32MeshIndex = m_Scene.pNode[i32NodeIndex].nIdx;
	SPODMesh* pMesh = &m_Scene.pMesh[i32MeshIndex];

	// bind the VBO for the mesh
	glBindBuffer(GL_ARRAY_BUFFER, m_puiVbo[i32MeshIndex]);
	// bind the index buffer, won't hurt if the handle is 0
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_puiIndexVbo[i32MeshIndex]);

	// Enable the vertex attribute arrays
	glEnableVertexAttribArray(VERTEX_ARRAY);
	glEnableVertexAttribArray(NORMAL_ARRAY);
	glEnableVertexAttribArray(TEXCOORD_ARRAY);

	// Set the vertex attribute offsets
	glVertexAttribPointer(VERTEX_ARRAY, 3, GL_FLOAT, GL_FALSE, pMesh->sVertex.nStride, pMesh->sVertex.pData);
	glVertexAttribPointer(NORMAL_ARRAY, 3, GL_FLOAT, GL_FALSE, pMesh->sNormals.nStride, pMesh->sNormals.pData);
	glVertexAttribPointer(TEXCOORD_ARRAY, 2, GL_FLOAT, GL_FALSE, pMesh->psUVW[0].nStride, pMesh->psUVW[0].pData);

	/*
		The geometry can be exported in 4 ways:
		- Indexed Triangle list
		- Non-Indexed Triangle list
		- Indexed Triangle strips
		- Non-Indexed Triangle strips
	*/
	if(pMesh->nNumStrips == 0)
	{
		if(m_puiIndexVbo[i32MeshIndex])
		{
			// Indexed Triangle list
			glDrawElements(GL_TRIANGLES, pMesh->nNumFaces*3, GL_UNSIGNED_SHORT, 0);
		}
		else
		{
			// Non-Indexed Triangle list
			glDrawArrays(GL_TRIANGLES, 0, pMesh->nNumFaces*3);
		}
	}
	else
	{
		for(int i = 0; i < (int)pMesh->nNumStrips; ++i)
		{
			int offset = 0;
			if(m_puiIndexVbo[i32MeshIndex])
			{
				// Indexed Triangle strips
				glDrawElements(GL_TRIANGLE_STRIP, pMesh->pnStripLength[i]+2, GL_UNSIGNED_SHORT, (GLshort*)(offset*2));
			}
			else
			{
				// Non-Indexed Triangle strips
				glDrawArrays(GL_TRIANGLE_STRIP, offset, pMesh->pnStripLength[i]+2);
			}
			offset += pMesh->pnStripLength[i]+2;
		}
	}

	// Safely disable the vertex attribute arrays
	glDisableVertexAttribArray(VERTEX_ARRAY);
	glDisableVertexAttribArray(NORMAL_ARRAY);
	glDisableVertexAttribArray(TEXCOORD_ARRAY);

	glBindBuffer(GL_ARRAY_BUFFER, 0);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
示例#10
0
int main( int argc, char **argv )
{
    int width = 1024, height=768;
    float widthf = (float) width, heightf = (float) height;
    double t;
    float fps = 0.f;

    // Initialise GLFW
    if( !glfwInit() )
    {
        fprintf( stderr, "Failed to initialize GLFW\n" );
        exit( EXIT_FAILURE );
    }

    // Force core profile on Mac OSX
#ifdef __APPLE__
    glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3);
    glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 2);
    glfwOpenWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#endif
    // Open a window and create its OpenGL context
    if( !glfwOpenWindow( width, height, 0,0,0,0, 24, 0, GLFW_WINDOW ) )
    {
        fprintf( stderr, "Failed to open GLFW window\n" );

        glfwTerminate();
        exit( EXIT_FAILURE );
    }

    glfwSetWindowTitle( "002_forward_a" );


    // Core profile is flagged as experimental in glew
#ifdef __APPLE__
    glewExperimental = GL_TRUE;
#endif
    GLenum err = glewInit();
    if (GLEW_OK != err)
    {
          /* Problem: glewInit failed, something is seriously wrong. */
          fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
          exit( EXIT_FAILURE );
    }

    // Ensure we can capture the escape key being pressed below
    glfwEnable( GLFW_STICKY_KEYS );

    // Enable vertical sync (on cards that support it)
    glfwSwapInterval( 1 );
    GLenum glerr = GL_NO_ERROR;
    glerr = glGetError();

    if (!imguiRenderGLInit(DroidSans_ttf, DroidSans_ttf_len))
    {
        fprintf(stderr, "Could not init GUI renderer.\n");
        exit(EXIT_FAILURE);
    }

    // Init viewer structures
    Camera camera;
    camera_defaults(camera);
    GUIStates guiStates;
    init_gui_states(guiStates);

    // GUI
    float intensity = 1.0;

    // Load images and upload textures
    GLuint textures[3];
    glGenTextures(3, textures);
    int x;
    int y;
    int comp; 
    unsigned char * diffuse = stbi_load("textures/spnza_bricks_a_diff.tga", &x, &y, &comp, 3);
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, textures[0]);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, x, y, 0, GL_RGB, GL_UNSIGNED_BYTE, diffuse);
    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);
    fprintf(stderr, "Diffuse %dx%d:%d\n", x, y, comp);
    unsigned char * spec = stbi_load("textures/spnza_bricks_a_spec.tga", &x, &y, &comp, 1);
    glActiveTexture(GL_TEXTURE1);
    glBindTexture(GL_TEXTURE_2D, textures[1]);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, x, y, 0, GL_RED, GL_UNSIGNED_BYTE, spec);
    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);
    fprintf(stderr, "Spec %dx%d:%d\n", x, y, comp);

    // Try to load and compile shader
    ShaderGLSL shader;
    const char * shaderFile = "002/1.glsl";
    //int status = load_shader_from_file(shader, shaderFile, ShaderGLSL::VERTEX_SHADER | ShaderGLSL::FRAGMENT_SHADER | ShaderGLSL::GEOMETRY_SHADER);
    int status = load_shader_from_file(shader, shaderFile, ShaderGLSL::VERTEX_SHADER | ShaderGLSL::FRAGMENT_SHADER);
    if ( status == -1 )
    {
        fprintf(stderr, "Error on loading  %s\n", shaderFile);
        exit( EXIT_FAILURE );
    }    

    // Apply shader
    GLuint program = shader.program;
    glUseProgram(program);
    GLuint projectionLocation = glGetUniformLocation(program, "Projection");
    GLuint viewLocation = glGetUniformLocation(program, "View");
    GLuint objectLocation = glGetUniformLocation(program, "Object");
    GLuint timeLocation = glGetUniformLocation(program, "Time");
    GLuint diffuseLocation = glGetUniformLocation(program, "Diffuse");
    GLuint specLocation = glGetUniformLocation(program, "Spec");
    GLuint intensityLocation = glGetUniformLocation(program, "Intensity");
    GLuint cameraPositionLocation = glGetUniformLocation(program, "CameraPosition");

    GLuint lightPositionLocation = glGetUniformLocation(program, "LightPosition");
    GLuint lightIntensityLocation = glGetUniformLocation(program, "LightIntensity");
    GLuint diffuseColorLocation = glGetUniformLocation(program, "DiffuseColor");
    GLuint specularColorLocation = glGetUniformLocation(program, "SpecularColor");
    GLuint specularFactorLocation = glGetUniformLocation(program, "SpecularFactor");

    GLuint lightPositionLocation2 = glGetUniformLocation(program, "LightPosition2");
    GLuint lightIntensityLocation2 = glGetUniformLocation(program, "LightIntensity2");
    GLuint diffuseColorLocation2 = glGetUniformLocation(program, "DiffuseColor2");
    GLuint specularColorLocation2 = glGetUniformLocation(program, "SpecularColor2");
    GLuint specularFactorLocation2 = glGetUniformLocation(program, "SpecularFactor2");

    GLuint spotLightExternalAngleLocation = glGetUniformLocation(program, "SpotLightExternalAngle");
    GLuint spotLightInternalAngleLocation = glGetUniformLocation(program, "SpotLightInternalAngle");


    // Load geometry
    int cube_triangleCount = 12;
    int cube_triangleList[] = {0, 1, 2, 2, 1, 3, 4, 5, 6, 6, 5, 7, 8, 9, 10, 10, 9, 11, 12, 13, 14, 14, 13, 15, 16, 17, 18, 19, 17, 20, 21, 22, 23, 24, 25, 26, };
    float cube_uvs[] = {0.f, 0.f, 0.f, 1.f, 1.f, 0.f, 1.f, 1.f, 0.f, 0.f, 0.f, 1.f, 1.f, 0.f, 1.f, 1.f, 0.f, 0.f, 0.f, 1.f, 1.f, 0.f, 1.f, 1.f, 0.f, 0.f, 0.f, 1.f, 1.f, 0.f, 1.f, 1.f, 0.f, 0.f, 0.f, 1.f, 1.f, 0.f,  1.f, 0.f,  1.f, 1.f,  0.f, 1.f,  1.f, 1.f,  0.f, 0.f, 0.f, 0.f, 1.f, 1.f,  1.f, 0.f,  };
    float cube_vertices[] = {-0.5, -0.5, 0.5, 0.5, -0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, -0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, -0.5, 0.5, -0.5, 0.5, 0.5 };
    float cube_normals[] = {0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, };
    int plane_triangleCount = 2;
    int plane_triangleList[] = {0, 1, 2, 2, 1, 3}; 
    float plane_uvs[] = {0.f, 0.f, 0.f, 10.f, 10.f, 0.f, 10.f, 10.f};
    float plane_vertices[] = {-50.0, -1.0, 50.0, 50.0, -1.0, 50.0, -50.0, -1.0, -50.0, 50.0, -1.0, -50.0};
    float plane_normals[] = {0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0};

    // Vertex Array Object
    GLuint vao[2];
    glGenVertexArrays(2, vao);

    // Vertex Buffer Objects
    GLuint vbo[8];
    glGenBuffers(8, vbo);

    // Cube
    glBindVertexArray(vao[0]);
    // Bind indices and upload data
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo[0]);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(cube_triangleList), cube_triangleList, GL_STATIC_DRAW);
    // Bind vertices and upload data
    glBindBuffer(GL_ARRAY_BUFFER, vbo[1]);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(GL_FLOAT)*3, (void*)0);
    glBufferData(GL_ARRAY_BUFFER, sizeof(cube_vertices), cube_vertices, GL_STATIC_DRAW);
    // Bind normals and upload data
    glBindBuffer(GL_ARRAY_BUFFER, vbo[2]);
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(GL_FLOAT)*3, (void*)0);
    glBufferData(GL_ARRAY_BUFFER, sizeof(cube_normals), cube_normals, GL_STATIC_DRAW);
    // Bind uv coords and upload data
    glBindBuffer(GL_ARRAY_BUFFER, vbo[3]);
    glEnableVertexAttribArray(2);
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(GL_FLOAT)*2, (void*)0);
    glBufferData(GL_ARRAY_BUFFER, sizeof(cube_uvs), cube_uvs, GL_STATIC_DRAW);

    // Plane
    glBindVertexArray(vao[1]);
    // Bind indices and upload data
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo[4]);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(plane_triangleList), plane_triangleList, GL_STATIC_DRAW);
    // Bind vertices and upload data
    glBindBuffer(GL_ARRAY_BUFFER, vbo[5]);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(GL_FLOAT)*3, (void*)0);
    glBufferData(GL_ARRAY_BUFFER, sizeof(plane_vertices), plane_vertices, GL_STATIC_DRAW);
    // Bind normals and upload data
    glBindBuffer(GL_ARRAY_BUFFER, vbo[6]);
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(GL_FLOAT)*3, (void*)0);
    glBufferData(GL_ARRAY_BUFFER, sizeof(plane_normals), plane_normals, GL_STATIC_DRAW);
    // Bind uv coords and upload data
    glBindBuffer(GL_ARRAY_BUFFER, vbo[7]);
    glEnableVertexAttribArray(2);
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(GL_FLOAT)*2, (void*)0);
    glBufferData(GL_ARRAY_BUFFER, sizeof(plane_uvs), plane_uvs, GL_STATIC_DRAW);

    // Unbind everything. Potentially illegal on some implementations
    glBindVertexArray(0);
    glBindBuffer(GL_ARRAY_BUFFER, 0);

    // Viewport 
    glViewport( 0, 0, width, height  );

    // Default states

    glm::vec3 lightPosition(0.0, 1.0, 10);
    float lightIntensity = 1.0f;
    glm::vec3 diffuseColor(1.0, 1.0, 1.0);
    glm::vec3 specularColor(1.0, 1.0, 1.0);
    float specularFactor = 100.f;

    glm::vec3 lightPosition2(1.0, 0.0, 10);
    float lightIntensity2 = 1.0f;
    glm::vec3 diffuseColor2(1.0, 0.0, 0.0);
    glm::vec3 specularColor2(1.0, 1.0, 1.0);
    float specularFactor2 = 100.f;

    float spotLightInternal = M_PI/32;
    float spotLightExternal = M_PI/16;

    bool checkedLight1 = true;
    bool checkedLight2 = false;
    bool checkedLight3 = false;

    do
    {
        t = glfwGetTime();
        glEnable(GL_DEPTH_TEST);

        // Mouse states
        int leftButton = glfwGetMouseButton( GLFW_MOUSE_BUTTON_LEFT );
        int rightButton = glfwGetMouseButton( GLFW_MOUSE_BUTTON_RIGHT );
        int middleButton = glfwGetMouseButton( GLFW_MOUSE_BUTTON_MIDDLE );

        if( leftButton == GLFW_PRESS )
            guiStates.turnLock = true;
        else
            guiStates.turnLock = false;

        if( rightButton == GLFW_PRESS )
            guiStates.zoomLock = true;
        else
            guiStates.zoomLock = false;

        if( middleButton == GLFW_PRESS )
            guiStates.panLock = true;
        else
            guiStates.panLock = false;

        // Camera movements
        int altPressed = glfwGetKey(GLFW_KEY_LSHIFT);
        if (!altPressed && (leftButton == GLFW_PRESS || rightButton == GLFW_PRESS || middleButton == GLFW_PRESS))
        {
            int x; int y;
            glfwGetMousePos(&x, &y);
            guiStates.lockPositionX = x;
            guiStates.lockPositionY = y;
        }
        if (altPressed == GLFW_PRESS)
        {
            int mousex; int mousey;
            glfwGetMousePos(&mousex, &mousey);
            int diffLockPositionX = mousex - guiStates.lockPositionX;
            int diffLockPositionY = mousey - guiStates.lockPositionY;
            if (guiStates.zoomLock)
            {
                float zoomDir = 0.0;
                if (diffLockPositionX > 0)
                    zoomDir = -1.f;
                else if (diffLockPositionX < 0 )
                    zoomDir = 1.f;
                camera_zoom(camera, zoomDir * GUIStates::MOUSE_ZOOM_SPEED);
            }
            else if (guiStates.turnLock)
            {
                camera_turn(camera, diffLockPositionY * GUIStates::MOUSE_TURN_SPEED,
                            diffLockPositionX * GUIStates::MOUSE_TURN_SPEED);

            }
            else if (guiStates.panLock)
            {
                camera_pan(camera, diffLockPositionX * GUIStates::MOUSE_PAN_SPEED,
                            diffLockPositionY * GUIStates::MOUSE_PAN_SPEED);
            }
            guiStates.lockPositionX = mousex;
            guiStates.lockPositionY = mousey;
        }
  
        // Get camera matrices
        glm::mat4 projection = glm::perspective(45.0f, widthf / heightf, 0.1f, 100.f); 
        glm::mat4 worldToView = glm::lookAt(camera.eye, camera.o, camera.up);
        glm::mat4 objectToWorld;

        // Clear the front buffer
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        // Bind textures
        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, textures[0]);
        glActiveTexture(GL_TEXTURE1);
        glBindTexture(GL_TEXTURE_2D, textures[1]);

        // Bind shader
        glUseProgram(program);

        // Upload uniforms
        glUniformMatrix4fv(projectionLocation, 1, 0, glm::value_ptr(projection));
        glUniformMatrix4fv(viewLocation, 1, 0, glm::value_ptr(worldToView));
        glUniformMatrix4fv(objectLocation, 1, 0, glm::value_ptr(objectToWorld));
        glUniform1f(timeLocation, t);
        glUniform3fv(cameraPositionLocation, 1, glm::value_ptr(camera.eye));
        glUniform1f(intensityLocation, intensity);
        glUniform1i(diffuseLocation, 0);
        glUniform1i(specLocation, 1);
        
        glUniform3fv(lightPositionLocation, 1, glm::value_ptr(lightPosition));
        glUniform1f(lightIntensityLocation, lightIntensity);
        glUniform3fv(diffuseColorLocation, 1, glm::value_ptr(diffuseColor));
        glUniform3fv(specularColorLocation, 1, glm::value_ptr(specularColor));
        glUniform1f(specularFactorLocation, specularFactor);

        glUniform3fv(lightPositionLocation2, 1, glm::value_ptr(lightPosition2));
        glUniform1f(lightIntensityLocation2, lightIntensity2);
        glUniform3fv(diffuseColorLocation2, 1, glm::value_ptr(diffuseColor2));
        glUniform3fv(specularColorLocation2, 1, glm::value_ptr(specularColor2));
        glUniform1f(specularFactorLocation2, specularFactor2);

        glUniform1f(spotLightInternalAngleLocation, spotLightInternal);
        glUniform1f(spotLightExternalAngleLocation, spotLightExternal);

        // Render vaos
        glBindVertexArray(vao[0]);
        glDrawElementsInstanced(GL_TRIANGLES, cube_triangleCount * 3, GL_UNSIGNED_INT, (void*)0, 4);
        glBindVertexArray(vao[1]);
        glDrawElements(GL_TRIANGLES, plane_triangleCount * 3, GL_UNSIGNED_INT, (void*)0);

#if 1
        // Draw UI
        glDisable(GL_DEPTH_TEST);
        glEnable(GL_BLEND);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
        glViewport(0, 0, width, height);

        unsigned char mbut = 0;
        int mscroll = 0;
        int mousex; int mousey;
        glfwGetMousePos(&mousex, &mousey);
        mousey = height - mousey;

        if( leftButton == GLFW_PRESS )
            mbut |= IMGUI_MBUT_LEFT;

        imguiBeginFrame(mousex, mousey, mbut, mscroll);
        int logScroll = 0;
        char lineBuffer[512];
        imguiBeginScrollArea("001", 0, 0, 200, height, &logScroll);
        sprintf(lineBuffer, "FPS %f", fps);
        imguiLabel(lineBuffer);
        
        int toggle = 0;
        toggle = imguiCollapse("Light1", "", checkedLight1);
            
        if(checkedLight1)
        { 
            imguiIndent();
            imguiIndent();
                imguiLabel("Light Position");
                imguiIndent();
                    imguiSlider("x", &lightPosition.x, -10, 10, 0.01);
                    imguiSlider("y", &lightPosition.y, -10, 10, 0.01);
                    imguiSlider("z", &lightPosition.z, -10, 10, 0.01);
                imguiUnindent();
                imguiSlider("Light Intensity", &lightIntensity, 0, 3, 0.01);
                imguiLabel("Diffuse Color");
                imguiIndent();
                    imguiSlider("r", &diffuseColor.x, 0, 1, 0.001);
                    imguiSlider("g", &diffuseColor.y, 0, 1, 0.001);
                    imguiSlider("b", &diffuseColor.z, 0, 1, 0.001);
                imguiUnindent();
                imguiLabel("Specular Color");
                imguiIndent();
                    imguiSlider("r", &specularColor.x, 0, 1, 0.001);
                    imguiSlider("g", &specularColor.y, 0, 1, 0.001);
                    imguiSlider("b", &specularColor.z, 0, 1, 0.001);
                imguiUnindent();
                imguiSlider("Specular Intensity", &specularFactor, 0, 100, 1);
            imguiUnindent();
            imguiUnindent();
        }
        if (toggle)
        {
            checkedLight1 = !checkedLight1;
        }

        toggle = imguiCollapse("Light2", "", checkedLight2);
        if(checkedLight2)
        { 
            imguiIndent();
            imguiIndent();
                imguiLabel("Light Position");
                imguiIndent();
                    imguiSlider("x", &lightPosition2.x, -10, 10, 0.01);
                    imguiSlider("y", &lightPosition2.y, -10, 10, 0.01);
                    imguiSlider("z", &lightPosition2.z, -10, 10, 0.01);
                imguiUnindent();
                imguiSlider("Light Intensity", &lightIntensity2, 0, 3, 0.01);
                imguiLabel("Diffuse Color");
                imguiIndent();
                    imguiSlider("r", &diffuseColor2.x, 0, 1, 0.001);
                    imguiSlider("g", &diffuseColor2.y, 0, 1, 0.001);
                    imguiSlider("b", &diffuseColor2.z, 0, 1, 0.001);
                imguiUnindent();
                imguiLabel("Specular Color");
                imguiIndent();
                    imguiSlider("r", &specularColor2.x, 0, 1, 0.001);
                    imguiSlider("g", &specularColor2.y, 0, 1, 0.001);
                    imguiSlider("b", &specularColor2.z, 0, 1, 0.001);
                imguiUnindent();
                imguiSlider("Specular Intensity", &specularFactor2, 0, 100, 1);
            imguiUnindent();
            imguiUnindent();
        }
        if (toggle)
        {
            checkedLight2 = !checkedLight2;
        }

        toggle = imguiCollapse("SpotLight", "", checkedLight3);
        if(checkedLight3)
        { 
            imguiIndent();
            imguiIndent();
                imguiSlider("External Angle", &spotLightExternal, 0, 2, 0.01);
                imguiSlider("Internal Angle", &spotLightInternal, 0, 2, 0.01);
            imguiUnindent();
            imguiUnindent();
        }
        if (toggle)
        {
            checkedLight3 = !checkedLight3;
        }

        imguiEndScrollArea();
        imguiEndFrame();
        imguiRenderGLDraw(width, height); 

        glDisable(GL_BLEND);
#endif
        
        // Check for errors
        GLenum err = glGetError();
        if(err != GL_NO_ERROR)
        {
            fprintf(stderr, "OpenGL Error : %s\n", gluErrorString(err));
            
        }

        // Swap buffers
        glfwSwapBuffers();

    } // Check if the ESC key was pressed or the window was closed
    while( glfwGetKey( GLFW_KEY_ESC ) != GLFW_PRESS &&
           glfwGetWindowParam( GLFW_OPENED ) );

    // Clean UI
    imguiRenderGLDestroy();

    // Close OpenGL window and terminate GLFW
    glfwTerminate();

    exit( EXIT_SUCCESS );
}
void
init()
{
    colorcube();

    // Create a checkerboard pattern
    for ( int i = 0; i < 64; i++ ) {
        for ( int j = 0; j < 64; j++ ) {
            GLubyte c = (((i & 0x8) == 0) ^ ((j & 0x8)  == 0)) * 255;
            image[i][j][0]  = c;
            image[i][j][1]  = c;
            image[i][j][2]  = c;
            image2[i][j][0] = c;
            image2[i][j][1] = 0;
            image2[i][j][2] = c;
        }
    }

    // Initialize texture objects
    glGenTextures( 2, textures );

    glBindTexture( GL_TEXTURE_2D, textures[0] );
    glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB, TextureSize, TextureSize, 0,
		  GL_RGB, GL_UNSIGNED_BYTE, image );
    glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
    glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
    glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
    glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );

    glBindTexture( GL_TEXTURE_2D, textures[1] );
    glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB, TextureSize, TextureSize, 0,
		  GL_RGB, GL_UNSIGNED_BYTE, image2 );
    glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
    glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
    glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
    glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );

    glActiveTexture( GL_TEXTURE0 );
    glBindTexture( GL_TEXTURE_2D, textures[0] );
    // Create a vertex array object
    GLuint vao;
    glGenVertexArraysAPPLE( 1, &vao );
    glBindVertexArrayAPPLE( vao );

    // Create and initialize a buffer object
    GLuint buffer;
    glGenBuffers( 1, &buffer );
    glBindBuffer( GL_ARRAY_BUFFER, buffer );
    glBufferData( GL_ARRAY_BUFFER,
		  sizeof(points) + sizeof(quad_colors) + sizeof(tex_coords),
		  NULL, GL_STATIC_DRAW );

    // Specify an offset to keep track of where we're placing data in our
    //   vertex array buffer.  We'll use the same technique when we
    //   associate the offsets with vertex attribute pointers.
    GLintptr offset = 0;
    glBufferSubData( GL_ARRAY_BUFFER, offset, sizeof(points), points );
    offset += sizeof(points);

    glBufferSubData( GL_ARRAY_BUFFER, offset,
		     sizeof(quad_colors), quad_colors );
    offset += sizeof(quad_colors);
    
    glBufferSubData( GL_ARRAY_BUFFER, offset, sizeof(tex_coords), tex_coords );

    // Load shaders and use the resulting shader program
    GLuint program = InitShader( "vshader_a8.glsl", "fshader_a8.glsl" );
    glUseProgram( program );

    // set up vertex arrays
    offset = 0;
    GLuint vPosition = glGetAttribLocation( program, "vPosition" );
    glEnableVertexAttribArray( vPosition );
    glVertexAttribPointer( vPosition, 4, GL_FLOAT, GL_FALSE, 0,
			   BUFFER_OFFSET(offset) );
    offset += sizeof(points);

    GLuint vColor = glGetAttribLocation( program, "vColor" ); 
    glEnableVertexAttribArray( vColor );
    glVertexAttribPointer( vColor, 4, GL_FLOAT, GL_FALSE, 0,
			   BUFFER_OFFSET(offset) );
    offset += sizeof(quad_colors);

    GLuint vTexCoord = glGetAttribLocation( program, "vTexCoord" );
    glEnableVertexAttribArray( vTexCoord );
    glVertexAttribPointer( vTexCoord, 2, GL_FLOAT, GL_FALSE, 0,
			   BUFFER_OFFSET(offset) );

    // Set the value of the fragment shader texture sampler variable
    //   ("texture") to the the appropriate texture unit. In this case,
    //   zero, for GL_TEXTURE0 which was previously set by calling
    //   glActiveTexture().
    glUniform1i( glGetUniformLocation(program, "texture"), 0 );

    theta = glGetUniformLocation( program, "theta" );
    
    glEnable( GL_DEPTH_TEST );
    
    glClearColor( 1.0, 1.0, 1.0, 1.0 );
}
示例#12
0
int main () {
  long it = 0;
  // start GL context and O/S window using the GLFW helper library
  if (!glfwInit ()) {
    fprintf (stderr, "ERROR: could not start GLFW3\n");
    return 1;
  } 
  printf ("main:");

	// uncomment these lines if on Apple OS X
  /*glfwWindowHint (GLFW_CONTEXT_VERSION_MAJOR, 3);
  glfwWindowHint (GLFW_CONTEXT_VERSION_MINOR, 2);
  glfwWindowHint (GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
  glfwWindowHint (GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);*/

  GLFWwindow* window = glfwCreateWindow (640, 480, "Hello Triangle", NULL, NULL);
  if (!window) {
    fprintf (stderr, "ERROR: could not open window with GLFW3\n");
    glfwTerminate();
    return 1;
  }
  glfwMakeContextCurrent (window);
                                  
  // start GLEW extension handler
  glewExperimental = GL_TRUE;
  glewInit ();

  // get version info
  const GLubyte* renderer = glGetString (GL_RENDERER); // get renderer string
  const GLubyte* version = glGetString (GL_VERSION); // version as a string
  printf ("Renderer: %s\n", renderer);
  printf ("OpenGL version supported %s\n", version);

  // tell GL to only draw onto a pixel if the shape is closer to the viewer
  glEnable (GL_DEPTH_TEST); // enable depth-testing
  glDepthFunc (GL_LESS); // depth-testing interprets a smaller value as "closer"

  /* OTHER STUFF GOES HERE NEXT */

  float points[] = {
     0.0f,  0.5f,  0.0f,
     0.5f, -0.5f,  0.0f,
    -0.5f, -0.5f,  0.0f
  };

  GLuint vbo = 0;
  glGenBuffers (1, &vbo);
  glBindBuffer (GL_ARRAY_BUFFER, vbo);
  glBufferData (GL_ARRAY_BUFFER, 9 * sizeof (float), points, GL_STATIC_DRAW);

  GLuint vao = 0;
  glGenVertexArrays (1, &vao);
  glBindVertexArray (vao);
  glEnableVertexAttribArray (0);
  glBindBuffer (GL_ARRAY_BUFFER, vbo);
  glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, 0, NULL);

  const char* vertex_shader =
  "#version 400\n"
  "in vec3 vp;"
  "void main () {"
  "  gl_Position = vec4 (vp, 1.0);"
  "}";

  const char* fragment_shader =
  "#version 400\n"
  "out vec4 frag_colour;"
  "void main () {"
  "  frag_colour = vec4 (0.5, 0.0, 0.5, 1.0);"
  "}";

  GLuint vs = glCreateShader (GL_VERTEX_SHADER);
  glShaderSource (vs, 1, &vertex_shader, NULL);
  glCompileShader (vs);
  GLuint fs = glCreateShader (GL_FRAGMENT_SHADER);
  glShaderSource (fs, 1, &fragment_shader, NULL);
  glCompileShader (fs);

  GLuint shader_programme = glCreateProgram ();
  glAttachShader (shader_programme, fs);
  glAttachShader (shader_programme, vs);
  glLinkProgram (shader_programme);

  while (!glfwWindowShouldClose (window)) {

    printf("iterations: %ld\n", it++);

    // wipe the drawing surface clear
    glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glUseProgram (shader_programme);
    glBindVertexArray (vao);
    // draw points 0-3 from the currently bound VAO with current in-use shader
    glDrawArrays (GL_TRIANGLES, 0, 3);
    // update other events like input handling 
    glfwPollEvents ();
    // put the stuff we've been drawing onto the display
    glfwSwapBuffers (window);
  }

  // close GL context and any other GLFW resources
  glfwTerminate();
  printf("EXIT");
  return 0;
}
    virtual void startup()
    {
        static const char * vs_source[] =
        {
            "#version 420 core                                                  \n"
            "                                                                   \n"
            "in vec4 position;                                                  \n"
            "                                                                   \n"
            /* "out VS_OUT                                                         \n"
            "{                                                                  \n"
            "    vec4 color;                                                    \n"
            "} vs_out;                                                          \n"*/
            "                                                                   \n"
            "void main(void)                                                    \n"
            "{                                                                  \n"
            "    gl_Position = position;              \n"
            // "    vs_out.color = position * 2.0 + vec4(0.5, 0.5, 0.5, 0.0);      \n"
            "}                                                                  \n"
        };

#if 0
        static const char * tcs_source[] =
        {
            "#version 420 core                                                                 \n"
            "                                                                                  \n"
            "layout (vertices = 4) out;                                                        \n"
            "                                                                                  \n"
            /* "in VS_OUT                                                                         \n"
            "{                                                                                 \n"
            "    vec4 color;                                                                   \n"
            "} vs_in[];                                                                        \n"*/
            "                                                                                  \n"
            "void main(void)                                                                   \n"
            "{                                                                                 \n"
            "    if (gl_InvocationID == 0)                                                     \n"
            "    {                                                                             \n"
            "        gl_TessLevelInner[0] = 4.0;                                               \n"
            "        gl_TessLevelInner[1] = 4.0;                                               \n"
            "        gl_TessLevelOuter[0] = 4.0;                                               \n"
            "        gl_TessLevelOuter[1] = 4.0;                                               \n"
            "        gl_TessLevelOuter[2] = 4.0;                                               \n"
            "        gl_TessLevelOuter[3] = 4.0;                                               \n"
            "    }                                                                             \n"
            "    gl_out[gl_InvocationID].gl_Position = gl_in[gl_InvocationID].gl_Position;     \n"
            "}                                                                                 \n"
        };
#endif

        static const char * tcs_source[] =
        {
            "#version 420 core                                                                 \n"
            "                                                                                  \n"
            "layout (vertices = 4) out;                                                        \n"
            "                                                                                  \n"
            /* "in VS_OUT                                                                         \n"
            "{                                                                                 \n"
            "    vec4 color;                                                                   \n"
            "} vs_in[];                                                                        \n"*/
            "                                                                                  \n"
            "uniform mat4 mv_matrix;                                                           \n"
            "uniform mat4 proj_matrix;                                                         \n"
            "                                                                                  \n"
            "void main(void)                                                                   \n"
            "{                                                                                 \n"
            "    vec4 pos[4];                                                                  \n"
            "    float tf[4];                                                                  \n"
            "    float t = 0.0;                                                                \n"
            "                                                                                  \n"
            "    int i;                                                                        \n"
            "                                                                                  \n"
            "    if (gl_InvocationID == 0)                                                     \n"
            "    {                                                                             \n"
            "        for (i = 0; i < 4; i++)                                                   \n"
            "        {                                                                         \n"
            "            pos[i] = proj_matrix * mv_matrix * gl_in[i].gl_Position;              \n"
            "        }                                                                         \n"
            "                                                                                  \n"
            "        tf[0] = max(2.0, distance(pos[0].xy / pos[0].w,                           \n"
            "                                  pos[1].xy / pos[1].w) * 16.0);                  \n"
            "        tf[1] = max(2.0, distance(pos[1].xy / pos[1].w,                           \n"
            "                                  pos[3].xy / pos[3].w) * 16.0);                  \n"
            "        tf[2] = max(2.0, distance(pos[2].xy / pos[2].w,                           \n"
            "                                  pos[3].xy / pos[3].w) * 16.0);                  \n"
            "        tf[3] = max(2.0, distance(pos[2].xy / pos[2].w,                           \n"
            "                                  pos[0].xy / pos[0].w) * 16.0);                  \n"
            "        for (i = 0; i < 4; i++)                                                   \n"
            "        {                                                                         \n"
            "            t = max(t, tf[i]);                                                           \n"
            "        }                                                                         \n"
            "                                                                                  \n"
            "        gl_TessLevelInner[0] = t;                             \n"
            "        gl_TessLevelInner[1] = t;                             \n"
            "        gl_TessLevelOuter[0] = tf[0];                                             \n"
            "        gl_TessLevelOuter[1] = tf[1];                                             \n"
            "        gl_TessLevelOuter[2] = tf[2];                                             \n"
            "        gl_TessLevelOuter[3] = tf[3];                                             \n"
            "    }                                                                             \n"
            "                                                                                  \n"
            "    gl_out[gl_InvocationID].gl_Position = gl_in[gl_InvocationID].gl_Position;     \n"
            "}                                                                                 \n"
        };

        static const char * tes_source[] =
        {
            "#version 420 core                                                                 \n"
            "                                                                                  \n"
            "layout (quads, fractional_odd_spacing, ccw) in;                                   \n"
            "                                                                                  \n"
            "uniform mat4 mv_matrix;                                                           \n"
            "uniform mat4 proj_matrix;                                                         \n"
            "                                                                                  \n"
            "out vec3 normal;                                                                  \n"
            "                                                                                  \n"
            "void main(void)                                                                   \n"
            "{                                                                                 \n"
            "    vec4 mid1 = mix(gl_in[0].gl_Position, gl_in[1].gl_Position, gl_TessCoord.x);  \n"
            "    vec4 mid2 = mix(gl_in[2].gl_Position, gl_in[3].gl_Position, gl_TessCoord.x);  \n"
            "    vec4 pos = mix(mid1, mid2, gl_TessCoord.y);                                   \n"
            "    pos.xyz = /* normalize*/(pos.xyz) * 0.25;                                          \n"
            "    normal = normalize(mat3(mv_matrix) * pos.xyz);                                \n"
            "    gl_Position = proj_matrix * mv_matrix * pos;                                  \n"
            "}                                                                                 \n"
        };

        static const char * fs_source[] =
        {
            "#version 420 core                                                  \n"
            "                                                                   \n"
            "out vec4 color;                                                    \n"
            "                                                                   \n"
            "in vec3 normal;                                                    \n"
            "                                                                   \n"
            "void main(void)                                                    \n"
            "{                                                                  \n"
            "    color = vec4(abs(normal), 1.0);                                \n"
            "}                                                                  \n"
        };

        program = glCreateProgram();
        GLuint fs = glCreateShader(GL_FRAGMENT_SHADER);
        glShaderSource(fs, 1, fs_source, NULL);
        glCompileShader(fs);

        GLuint vs = glCreateShader(GL_VERTEX_SHADER);
        glShaderSource(vs, 1, vs_source, NULL);
        glCompileShader(vs);

        GLuint tcs = glCreateShader(GL_TESS_CONTROL_SHADER);
        glShaderSource(tcs, 1, tcs_source, NULL);
        glCompileShader(tcs);

        GLuint tes = glCreateShader(GL_TESS_EVALUATION_SHADER);
        glShaderSource(tes, 1, tes_source, NULL);
        glCompileShader(tes);

        glAttachShader(program, vs);
        glAttachShader(program, tcs);
        glAttachShader(program, tes);
        glAttachShader(program, fs);

        glLinkProgram(program);

        mv_location = glGetUniformLocation(program, "mv_matrix");
        proj_location = glGetUniformLocation(program, "proj_matrix");

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

        static const GLushort vertex_indices[] =
        {
            0, 1, 2, 3,
            2, 3, 4, 5,
            4, 5, 6, 7,
            6, 7, 0, 1,
            0, 2, 6, 4,
            1, 7, 3, 5
        };

        static const GLfloat vertex_positions[] =
        {
            -0.25f, -0.25f, -0.25f,
            -0.25f,  0.25f, -0.25f,
             0.25f, -0.25f, -0.25f,
             0.25f,  0.25f, -0.25f,
             0.25f, -0.25f,  0.25f,
             0.25f,  0.25f,  0.25f,
            -0.25f, -0.25f,  0.25f,
            -0.25f,  0.25f,  0.25f,
        };

        glGenBuffers(1, &position_buffer);
        glBindBuffer(GL_ARRAY_BUFFER, position_buffer);
        glBufferData(GL_ARRAY_BUFFER,
                     sizeof(vertex_positions),
                     vertex_positions,
                     GL_STATIC_DRAW);
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, NULL);
        glEnableVertexAttribArray(0);

        glGenBuffers(1, &index_buffer);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, index_buffer);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER,
                     sizeof(vertex_indices),
                     vertex_indices,
                     GL_STATIC_DRAW);

        glEnable(GL_CULL_FACE);
        // glFrontFace(GL_CW);

        glEnable(GL_DEPTH_TEST);
        glDepthFunc(GL_LEQUAL);

        // glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
    }
示例#14
0
void assignment1_app::render(double currentTime)
{
	const float f = (float)currentTime;
	glUseProgram(per_vertex ? per_vertex_program : per_fragment_program);

#pragma region Calculations for mouse interaction camera rotation and translation matrix
	float fAngle = 0.0f;
	vmath::vec3 axis_in_camera_coord = (0.0f, 1.0f, 0.0f);
	if (iCurMouseX != iPrevMouseX || iCurMouseY != iPrevMouseY) {
		// Arcball Rotation
		if (bRotate) {
			vmath::vec3 va = getArcballVector(iPrevMouseX, iPrevMouseY);
			vmath::vec3 vb = getArcballVector(iCurMouseX, iCurMouseY);
			fAngle = acos(fmin(1.0f, vmath::dot(va, vb)));
			axis_in_camera_coord = vmath::cross(va, vb);
			axis_in_camera_coord = vmath::normalize(axis_in_camera_coord);
			iPrevMouseX = iCurMouseX;
			iPrevMouseY = iCurMouseY;
			rotationMatrix *= vmath::rotate(vmath::degrees(fAngle), axis_in_camera_coord);
		}
		// Zoom in and out
		if (bZoom) {
			fZpos += (iCurMouseY - iPrevMouseY);
			if (fZpos > 500)
			{
				fZpos = 500;
			}
			else if (fZpos < 10)
			{
				fZpos = 10;
			}
			iPrevMouseY = iCurMouseY;
			iPrevMouseX = iCurMouseX;
		}
		// Pan camera left, right, up, and down
		if (bPan) {
			fXpos += (iCurMouseX - iPrevMouseX);
			fYpos += (iCurMouseY - iPrevMouseY);
			iPrevMouseY = iCurMouseY;
			iPrevMouseX = iCurMouseX;
			translationMatrix = vmath::translate(fXpos / (info.windowWidth / fZpos), -fYpos / (info.windowWidth / fZpos), 0.0f);
		}
		//Light position tracks with the camera
		lightPos = vmath::vec4(iLightPosX * translationMatrix[0][0] + iLightPosX * translationMatrix[0][1] + iLightPosX * translationMatrix[0][2],
			iLightPosY * translationMatrix[1][0] + iLightPosY * translationMatrix[1][1] + iLightPosY * translationMatrix[1][2],
			iLightPosZ * translationMatrix[2][0] + iLightPosZ * translationMatrix[2][1] + iLightPosZ * translationMatrix[2][2],
			1.0f
			);
		lightPos = vmath::vec4(lightPos[0] * rotationMatrix[0][0] + lightPos[0] * rotationMatrix[0][1] + lightPos[0] * rotationMatrix[0][2],
			lightPos[1] * rotationMatrix[1][0] + lightPos[1] * rotationMatrix[1][1] + lightPos[1] * rotationMatrix[1][2],
			lightPos[2] * rotationMatrix[2][0] + lightPos[2] * rotationMatrix[2][1] + lightPos[2] * rotationMatrix[2][2],
			1.0f
			);
	}
#pragma endregion

	glViewport(0, 0, info.windowWidth, info.windowHeight);

	// Create sky blue background
	glClearBufferfv(GL_COLOR, 0, skyBlue);
	glClearBufferfv(GL_DEPTH, 0, ones);

	// Set up view and perspective matrix
	vmath::vec3 view_position = vmath::vec3(0.0f, 0.0f, fZpos);
	vmath::mat4 view_matrix = vmath::lookat(view_position,
		vmath::vec3(0.0f, 0.0f, 0.0f),
		vmath::vec3(0.0f, 1.0f, 0.0f));
	view_matrix *= translationMatrix;
	view_matrix *= rotationMatrix;
	vmath::mat4 perspective_matrix = vmath::perspective(50.0f, (float)info.windowWidth / (float)info.windowHeight, 0.1f, 1000.0f);

	glUnmapBuffer(GL_UNIFORM_BUFFER); //release the mapping of a buffer object's data store into the client's address space
	glBindBufferBase(GL_UNIFORM_BUFFER, 0, uniforms_buffer);
	uniforms_block * block = (uniforms_block *)glMapBufferRange(GL_UNIFORM_BUFFER, 0, sizeof(uniforms_block), GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT);

#pragma region Uniforms that remain constant for all geometery
	block->proj_matrix = perspective_matrix;
	block->lightPos = lightPos;
#pragma endregion

#pragma region Draw Sphere
	glBindVertexArray(sphere_vao);
	glUnmapBuffer(GL_UNIFORM_BUFFER);
	glBindBufferBase(GL_UNIFORM_BUFFER, 0, uniforms_buffer);

	block = (uniforms_block *)glMapBufferRange(GL_UNIFORM_BUFFER, 0, sizeof(uniforms_block), GL_MAP_WRITE_BIT);
	vmath::mat4 model_matrix =
		vmath::translate(-9.3f, -16.0f, 1.0f) *
		vmath::scale(6.0f);
	block->mv_matrix = view_matrix * model_matrix;
	block->view_matrix = view_matrix;
	block->uni_color = purple;
	block->useUniformColor = useUniformColor;
	block->invertNormals = falseVec;
	block->isSphere = trueVec;

	glCullFace(GL_BACK);
	object.render();
#pragma endregion

	glUnmapBuffer(GL_UNIFORM_BUFFER); //release the mapping of a buffer object's data store into the client's address space
	glBindBufferBase(GL_UNIFORM_BUFFER, 0, uniforms_buffer);
	block = (uniforms_block *)glMapBufferRange(GL_UNIFORM_BUFFER, 0, sizeof(uniforms_block), GL_MAP_WRITE_BIT);

#pragma region Uniforms that remain constant for cubes
	block->uni_color = orange;
	block->useUniformColor = falseVec;
	block->isSphere = falseVec;
#pragma endregion

#pragma region bind cube vertex data
	glBindVertexArray(cube_vao);

	glBindBuffer(GL_ARRAY_BUFFER, buffer);
	glEnableVertexAttribArray(0); //enable or disable a generic vertex attribute array
	glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0); //define an array of generic vertex attribute data void glVertexAttribIPointer(GLuint index, GLint size, GLenum type, GLsizei stride, const GLvoid * pointer)

	glBindBuffer(GL_ARRAY_BUFFER, normalsBuffer);
	glEnableVertexAttribArray(1); //enable or disable a generic vertex attribute array
	glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 0, 0); //define an array of generic vertex attribute data void glVertexAttribIPointer(GLuint index, GLint size, GLenum type, GLsizei stride, const GLvoid * pointer)

	glBindBuffer(GL_ARRAY_BUFFER, colorBuffer);
	glEnableVertexAttribArray(2); //enable or disable a generic vertex attribute array
	glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, 0, 0); //define an array of generic vertex attribute data void glVertexAttribIPointer(GLuint index, GLint size, GLenum type, GLsizei stride, const GLvoid * pointer)

	glUnmapBuffer(GL_UNIFORM_BUFFER);
	glBindBufferBase(GL_UNIFORM_BUFFER, 0, uniforms_buffer);
	block = (uniforms_block *)glMapBufferRange(GL_UNIFORM_BUFFER, 0, sizeof(uniforms_block), GL_MAP_WRITE_BIT);
#pragma endregion

#pragma region Draw Room

	model_matrix =
		//vmath::rotate((float)currentTime * 14.5f, 0.0f, 1.0f, 0.0f) * //used to constantly rotate
		vmath::rotate(45.0f, 0.0f, 1.0f, 0.0f)*
		vmath::scale(22.0f);

	block->mv_matrix = view_matrix * model_matrix;
	block->view_matrix = view_matrix;
	block->invertNormals = falseVec;

	glCullFace(GL_FRONT);
	glDrawArrays(GL_TRIANGLES, 0, numberOfCubeVertices);

#pragma endregion

#pragma region Draw Cube

	glUnmapBuffer(GL_UNIFORM_BUFFER); //release the mapping of a buffer object's data store into the client's address space
	glBindBufferBase(GL_UNIFORM_BUFFER, 0, uniforms_buffer);
	block = (uniforms_block *)glMapBufferRange(GL_UNIFORM_BUFFER, 0, sizeof(uniforms_block), GL_MAP_WRITE_BIT);

	model_matrix =
		vmath::rotate(0.0f, 0.0f, 1.0f, 0.0f) *
		vmath::translate(10.0f, -17.3f, -1.0f) *
		vmath::scale(5.0f);

	block->mv_matrix = view_matrix * model_matrix;
	block->view_matrix = view_matrix;
	block->useUniformColor = falseVec;
	block->invertNormals = trueVec;

	glCullFace(GL_BACK);
	glDrawArrays(GL_TRIANGLES, 0, numberOfCubeVertices);
#pragma endregion
}
示例#15
0
文件: cube.c 项目: qioixiy/notes
static void draw()
{
	Matrix modelview;
	static const GLfloat vVertices[] = {
        // front
        -1.0f, -1.0f, +1.0f, // point blue
        +1.0f, -1.0f, +1.0f, // point magenta
        -1.0f, +1.0f, +1.0f, // point cyan
        +1.0f, +1.0f, +1.0f, // point white
        // back
        +1.0f, -1.0f, -1.0f, // point red
        -1.0f, -1.0f, -1.0f, // point black
        +1.0f, +1.0f, -1.0f, // point yellow
        -1.0f, +1.0f, -1.0f, // point green
        // right
        +1.0f, -1.0f, +1.0f, // point magenta
        +1.0f, -1.0f, -1.0f, // point red
        +1.0f, +1.0f, +1.0f, // point white
        +1.0f, +1.0f, -1.0f, // point yellow
        // left
        -1.0f, -1.0f, -1.0f, // point black
        -1.0f, -1.0f, +1.0f, // point blue
        -1.0f, +1.0f, -1.0f, // point green
        -1.0f, +1.0f, +1.0f, // point cyan
        // top
        -1.0f, +1.0f, +1.0f, // point cyan
        +1.0f, +1.0f, +1.0f, // point white
        -1.0f, +1.0f, -1.0f, // point green
        +1.0f, +1.0f, -1.0f, // point yellow
        // bottom
        -1.0f, -1.0f, -1.0f, // point black
        +1.0f, -1.0f, -1.0f, // point red
        -1.0f, -1.0f, +1.0f, // point blue
        +1.0f, -1.0f, +1.0f  // point magenta
	};

	static const GLfloat vColors[] = {
        // front
        0.0f,  0.0f,  1.0f, // blue
        1.0f,  0.0f,  1.0f, // magenta
        0.0f,  1.0f,  1.0f, // cyan
        1.0f,  1.0f,  1.0f, // white
        // back
        1.0f,  0.0f,  0.0f, // red
        0.0f,  0.0f,  0.0f, // black
        1.0f,  1.0f,  0.0f, // yellow
        0.0f,  1.0f,  0.0f, // green
        // right
        1.0f,  0.0f,  1.0f, // magenta
        1.0f,  0.0f,  0.0f, // red
        1.0f,  1.0f,  1.0f, // white
        1.0f,  1.0f,  0.0f, // yellow
        // left
        0.0f,  0.0f,  0.0f, // black
        0.0f,  0.0f,  1.0f, // blue
        0.0f,  1.0f,  0.0f, // green
        0.0f,  1.0f,  1.0f, // cyan
        // top
        0.0f,  1.0f,  1.0f, // cyan
        1.0f,  1.0f,  1.0f, // white
        0.0f,  1.0f,  0.0f, // green
        1.0f,  1.0f,  0.0f, // yellow
        // bottom
        0.0f,  0.0f,  0.0f, // black
        1.0f,  0.0f,  0.0f, // red
        0.0f,  0.0f,  1.0f, // blue
        1.0f,  0.0f,  1.0f  // magenta
	};

	static const GLfloat vNormals[] = {
        // front
        +0.0f, +0.0f, +1.0f, // forward
        +0.0f, +0.0f, +1.0f, // forward
        +0.0f, +0.0f, +1.0f, // forward
        +0.0f, +0.0f, +1.0f, // forward
        // back
        +0.0f, +0.0f, -1.0f, // backbard
        +0.0f, +0.0f, -1.0f, // backbard
        +0.0f, +0.0f, -1.0f, // backbard
        +0.0f, +0.0f, -1.0f, // backbard
        // right
        +1.0f, +0.0f, +0.0f, // right
        +1.0f, +0.0f, +0.0f, // right
        +1.0f, +0.0f, +0.0f, // right
        +1.0f, +0.0f, +0.0f, // right
        // left
        -1.0f, +0.0f, +0.0f, // left
        -1.0f, +0.0f, +0.0f, // left
        -1.0f, +0.0f, +0.0f, // left
        -1.0f, +0.0f, +0.0f, // left
        // top
        +0.0f, +1.0f, +0.0f, // up
        +0.0f, +1.0f, +0.0f, // up
        +0.0f, +1.0f, +0.0f, // up
        +0.0f, +1.0f, +0.0f, // up
        // bottom
        +0.0f, -1.0f, +0.0f, // down
        +0.0f, -1.0f, +0.0f, // down
        +0.0f, -1.0f, +0.0f, // down
        +0.0f, -1.0f, +0.0f  // down
	};

	static const GLfloat vTexUVs[] = {
        // front
        0.1f,  0.9f,
        0.9f,  0.9f,
        0.1f,  0.1f,
        0.9f,  0.1f,
        // back
        0.1f,  0.9f,
        0.9f,  0.9f,
        0.1f,  0.1f,
        0.9f,  0.1f,
        // right
        0.1f,  0.9f,
        0.9f,  0.9f,
        0.1f,  0.1f,
        0.9f,  0.1f,
        // left
        0.1f,  0.9f,
        0.9f,  0.9f,
        0.1f,  0.1f,
        0.9f,  0.1f,
        // top
        0.1f,  0.9f,
        0.9f,  0.9f,
        0.1f,  0.1f,
        0.9f,  0.1f,
        // bottom
        0.1f,  0.9f,
        0.9f,  0.9f,
        0.1f,  0.1f,
        0.9f,  0.1f,
	};

	/* clear the color buffer */
	glClearColor(0.5, 0.5, 0.5, 1.0);
	glClear(GL_COLOR_BUFFER_BIT);

	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, vVertices);
	glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, vNormals);
	glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, vColors);
	glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, 0, vTexUVs);
	glEnableVertexAttribArray(0);
	glEnableVertexAttribArray(1);
	glEnableVertexAttribArray(2);
	glEnableVertexAttribArray(3);

    float distance = 8.0;
    static int i = 0;
    i++;
	MatrixLoadIdentity(&modelview);
	Translate(&modelview, 0.0f, 0.0f, -distance);
	Rotate(&modelview, 45.0f + (0.25f * i), 1.0f, 0.0f, 0.0f);
	Rotate(&modelview, 45.0f - (0.5f * i), 0.0f, 1.0f, 0.0f);
	Rotate(&modelview, 10.0f + (0.15f * i), 0.0f, 0.0f, 1.0f);

	GLfloat aspect = 512/512;
    float fov = 45;
	Matrix projection;
	MatrixLoadIdentity(&projection);
	Perspective(&projection, fov, aspect, 1.0f, 10.0f);

	Matrix modelviewprojection;
	MatrixLoadIdentity(&modelviewprojection);
	MatrixMultiply(&modelviewprojection, &modelview, &projection);

	float normal[9];
	normal[0] = modelview.m[0][0];
	normal[1] = modelview.m[0][1];
	normal[2] = modelview.m[0][2];
	normal[3] = modelview.m[1][0];
	normal[4] = modelview.m[1][1];
	normal[5] = modelview.m[1][2];
	normal[6] = modelview.m[2][0];
	normal[7] = modelview.m[2][1];
	normal[8] = modelview.m[2][2];

	glUniformMatrix4fv(modelviewmatrix, 1, GL_FALSE, &modelview.m[0][0]);
	glUniformMatrix4fv(modelviewprojectionmatrix,
                       1, GL_FALSE, &modelviewprojection.m[0][0]);
	glUniformMatrix3fv(normalmatrix, 1, GL_FALSE, normal);

	glEnable(GL_CULL_FACE);

	glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
	glDrawArrays(GL_TRIANGLE_STRIP, 4, 4);
	glDrawArrays(GL_TRIANGLE_STRIP, 8, 4);
	glDrawArrays(GL_TRIANGLE_STRIP, 12, 4);
	glDrawArrays(GL_TRIANGLE_STRIP, 16, 4);
	glDrawArrays(GL_TRIANGLE_STRIP, 20, 4);
}
void initGL()
{
	/* Initialize GLEW; this gives us access to OpenGL Extensions.
	 */
	glewInit();  

	/* Print information about OpenGL and ensure that we've got at a context 
	 * that supports least OpenGL 3.0. Then setup the OpenGL Debug message
	 * mechanism.
	 */
	startupGLDiagnostics();
	setupGLDebugMessages();

	/* Workaround for AMD. It might no longer be necessary, but I dunno if we
	 * are ever going to remove it. (Consider it a piece of living history.)
	 */
	if( !glBindFragDataLocation )
	{
		glBindFragDataLocation = glBindFragDataLocationEXT;
	}

	/* As a general rule, you shouldn't need to change anything before this 
	 * comment in initGL().
	 */

	// Define the positions for each of the three vertices of the triangle
	const float positions[] = {
		//	 X      Y     Z
		0.0f,   0.5f, 1.0f,		// v0
		-0.5f,  -0.5f, 1.0f,	// v1
		0.5f,  -0.5f, 1.0f		// v2
	};

	// Define the colors for each of the three vertices of the triangle
	const float colors[] = {
		//  R     G		B
		1.0f, 1.0f, 1.0f,		// White
		1.0f, 1.0f, 1.0f,		// White
		1.0f, 1.0f, 1.0f		// White
	};

	// Create a handle for the position vertex buffer object
	// See OpenGL Spec §2.9 Buffer Objects 
	// - http://www.cse.chalmers.se/edu/course/TDA361/glspec30.20080923.pdf#page=54
	GLuint positionBuffer; 
	glGenBuffers( 1, &positionBuffer );
	// Set the newly created buffer as the current one
	glBindBuffer( GL_ARRAY_BUFFER, positionBuffer );
	// Send the vertex position data to the current buffer
	glBufferData( GL_ARRAY_BUFFER, sizeof(positions), positions, GL_STATIC_DRAW );

	// Create a handle for the vertex color buffer
	GLuint colorBuffer; 
	glGenBuffers( 1, &colorBuffer );
	// Set the newly created buffer as the current one
	glBindBuffer( GL_ARRAY_BUFFER, colorBuffer );	
	// Send the vertex color data to the current buffer
	glBufferData( GL_ARRAY_BUFFER, sizeof(colors), colors, GL_STATIC_DRAW );

	//******* Connect triangle data with the vertex array object *******
	//
	// Connect the vertex buffer objects to the vertex array object
	// See OpenGL Spec §2.10 
	// - http://www.cse.chalmers.se/edu/course/TDA361/glspec30.20080923.pdf#page=64
	glGenVertexArrays(1, &vertexArrayObject);

	// Bind the vertex array object
	// The following calls will affect this vertex array object.
	glBindVertexArray(vertexArrayObject);
	// Makes positionBuffer the current array buffer for subsequent calls.
	glBindBuffer( GL_ARRAY_BUFFER, positionBuffer );
	// Attaches positionBuffer to vertexArrayObject, in the 0th attribute location
	glVertexAttribPointer(0, 3, GL_FLOAT, false/*normalized*/, 0/*stride*/, 0/*offset*/ );	

	// Makes colorBuffer the current array buffer for subsequent calls.
	glBindBuffer( GL_ARRAY_BUFFER, colorBuffer );
	// Attaches colorBuffer to vertexArrayObject, in the 1st attribute location
	glVertexAttribPointer(1, 3, GL_FLOAT, false/*normalized*/, 0/*stride*/, 0/*offset*/ );

	glEnableVertexAttribArray(0); // Enable the vertex position attribute
	glEnableVertexAttribArray(1); // Enable the vertex color attribute 


	///////////////////////////////////////////////////////////////////////////
	// Create shaders
	///////////////////////////////////////////////////////////////////////////	

	// See OpenGL spec §2.20 http://www.cse.chalmers.se/edu/course/TDA361/glspec30.20080923.pdf#page=104&zoom=75
	GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
	GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);

	// Invoke helper functions (in glutil.h/cpp) to load text files for vertex and fragment shaders.
	const char *vs = textFileRead("simple.vert");
	const char *fs = textFileRead("simple.frag");

	glShaderSource(vertexShader, 1, &vs, NULL);
	glShaderSource(fragmentShader, 1, &fs, NULL);

	// we are now done with the source and can free the file data, textFileRead uses new [] to.
  // allocate the memory so we must free it using delete [].
	delete [] vs;
	delete [] fs;

	// Compile the shader, translates into internal representation and checks for errors.
	glCompileShader(vertexShader);
	int compileOK;
	// check for compiler errors in vertex shader.
	glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &compileOK);
	if(!compileOK) {
		std::string err = GetShaderInfoLog(vertexShader);
		fatal_error( err );
		return;
	}

	// Compile the shader, translates into internal representation and checks for errors.
	glCompileShader(fragmentShader);
	// check for compiler errors in fragment shader.
	glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &compileOK);
	if(!compileOK) {
		std::string err = GetShaderInfoLog(fragmentShader);
		fatal_error( err );
		return;
	}

	// Create a program object and attach the two shaders we have compiled, the program object contains
	// both vertex and fragment shaders as well as information about uniforms and attributes common to both.
	shaderProgram = glCreateProgram();
	glAttachShader(shaderProgram, fragmentShader);
	glAttachShader(shaderProgram, vertexShader);

	// Now that the fragment and vertex shader has been attached, we no longer need these two separate objects and should delete them.
	// The attachment to the shader program will keep them alive, as long as we keep the shaderProgram.
	glDeleteShader( vertexShader );
	glDeleteShader( fragmentShader );

	// We have previously (in the glVertexAttribPointer calls) decided that our 
	// vertex position data will be the 0th attribute. Bind the attribute with 
	// name "position" to the 0th stream
	glBindAttribLocation(shaderProgram, 0, "position"); 
	// And bind the attribute called "color" in the shader to the 1st attribute
	// stream. 
	glBindAttribLocation(shaderProgram, 1, "color");

	// This tells OpenGL which draw buffer the fragment shader out variable 'fragmentColor' will end up in.
	// Since we only use one output and draw buffer this is actually redundant, as the default will be correct.
	glBindFragDataLocation(shaderProgram, 0, "fragmentColor");

	// Link the different shaders that are bound to this program, this creates a final shader that 
	// we can use to render geometry with.
	glLinkProgram(shaderProgram);

	// Check for linker errors, many errors, such as mismatched in and out variables between 
	// vertex/fragment shaders,  do not appear before linking.
	{
		GLint linkOk = 0;
		glGetProgramiv(shaderProgram, GL_LINK_STATUS, &linkOk);
		if(!linkOk) 
		{
			std::string err = GetShaderInfoLog(shaderProgram);
			fatal_error( err );
			return;
		}
	}
}
示例#17
0
int
glw_opengl_shaders_init(glw_root_t *gr)
{
  glw_backend_root_t *gbr = &gr->gr_be;
  char path[512];
  GLuint vs, fs;

  SHADERPATH("v1.glsl");
  vs = glw_compile_shader(path, GL_VERTEX_SHADER, gr);

  SHADERPATH("f_tex.glsl");
  fs = glw_compile_shader(path, GL_FRAGMENT_SHADER, gr);
  gbr->gbr_renderer_tex = glw_link_program(gbr, "Texture", vs, fs);
  glDeleteShader(fs);

  SHADERPATH("f_tex_stencil.glsl");
  fs = glw_compile_shader(path, GL_FRAGMENT_SHADER, gr);
  gbr->gbr_renderer_tex_stencil = 
    glw_link_program(gbr, "TextureStencil", vs, fs);
  glDeleteShader(fs);

  SHADERPATH("f_tex_blur.glsl");
  fs = glw_compile_shader(path, GL_FRAGMENT_SHADER, gr);
  gbr->gbr_renderer_tex_blur = glw_link_program(gbr, "TextureBlur", vs, fs);
  glDeleteShader(fs);

  SHADERPATH("f_tex_stencil_blur.glsl");
  fs = glw_compile_shader(path, GL_FRAGMENT_SHADER, gr);
  gbr->gbr_renderer_tex_stencil_blur =
    glw_link_program(gbr, "TextureStencilBlur", vs, fs);
  glDeleteShader(fs);

  SHADERPATH("f_flat.glsl");
  fs = glw_compile_shader(path, GL_FRAGMENT_SHADER, gr);
  gbr->gbr_renderer_flat = glw_link_program(gbr, "Flat", vs, fs);
  glDeleteShader(fs);

  SHADERPATH("f_flat_stencil.glsl");
  fs = glw_compile_shader(path, GL_FRAGMENT_SHADER, gr);
  gbr->gbr_renderer_flat_stencil = glw_link_program(gbr, "FlatStencil", vs, fs);
  glDeleteShader(fs);

  glDeleteShader(vs);

  //    gbr->gbr_renderer_draw = glw_renderer_shader;


  // yuv2rgb Video renderer

  SHADERPATH("yuv2rgb_v.glsl");
  vs = glw_compile_shader(path, GL_VERTEX_SHADER, gr);


  SHADERPATH("yuv2rgb_1f_norm.glsl");
  fs = glw_compile_shader(path, GL_FRAGMENT_SHADER, gr);
  gbr->gbr_yuv2rgb_1f = glw_link_program(gbr, "yuv2rgb_1f_norm", vs, fs);
  glDeleteShader(fs);

  SHADERPATH("yuv2rgb_2f_norm.glsl");
  fs = glw_compile_shader(path, GL_FRAGMENT_SHADER, gr);
  gbr->gbr_yuv2rgb_2f = glw_link_program(gbr, "yuv2rgb_2f_norm", vs, fs);
  glDeleteShader(fs);
  glDeleteShader(vs);

  // rgb2rgb Video renderer

  SHADERPATH("rgb2rgb_v.glsl");
  vs = glw_compile_shader(path, GL_VERTEX_SHADER, gr);


  SHADERPATH("rgb2rgb_1f_norm.glsl");
  fs = glw_compile_shader(path, GL_FRAGMENT_SHADER, gr);
  gbr->gbr_rgb2rgb_1f = glw_link_program(gbr, "rgb2rgb_1f_norm", vs, fs);
  glDeleteShader(fs);

  SHADERPATH("rgb2rgb_2f_norm.glsl");
  fs = glw_compile_shader(path, GL_FRAGMENT_SHADER, gr);
  gbr->gbr_rgb2rgb_2f = glw_link_program(gbr, "rgb2rgb_2f_norm", vs, fs);
  glDeleteShader(fs);
  glDeleteShader(vs);

  gr->gr_be_render_unlocked = render_unlocked;
  glGenBuffers(1, &gbr->gbr_vbo);

  glEnableVertexAttribArray(0);
  glEnableVertexAttribArray(1);
  glEnableVertexAttribArray(2);

  prop_set_string(prop_create(gr->gr_prop_ui, "rendermode"),
		  "OpenGL VP/FP shaders");


#if ENABLE_GLW_BACKEND_OPENGL
  glMatrixMode(GL_PROJECTION);
  glLoadMatrixf(projection);
  glMatrixMode(GL_MODELVIEW);
#endif

  return 0;
}
示例#18
0
void Scene::init()
{
    _shaderProgram = createShaderProgramWithFilenames("PosColorLocalTransform.vert", "ColorPassthrough.frag");
    glUseProgram(_shaderProgram);
    printOpenGLError();
    
    // Uniforms
	modelToCameraMatrixUniform = glGetUniformLocation(_shaderProgram, "modelToCameraMatrix");
	cameraToClipMatrixUniform = glGetUniformLocation(_shaderProgram, "cameraToClipMatrix");
    
    // Matrix
    float fzNear = 1.0f; float fzFar = 45.0f;
    
	cameraToClipMatrix[0].x = frustumScale;
	cameraToClipMatrix[1].y = frustumScale;
	cameraToClipMatrix[2].z = (fzFar + fzNear) / (fzNear - fzFar);
	cameraToClipMatrix[2].w = -1.0f;
	cameraToClipMatrix[3].z = (2 * fzFar * fzNear) / (fzNear - fzFar);
    
	glUniformMatrix4fv(cameraToClipMatrixUniform, 1, GL_FALSE, glm::value_ptr(cameraToClipMatrix));
    
    // Vertex buffer objects
    glGenBuffers(1, &_vertexBufferObject);
    
	glBindBuffer(GL_ARRAY_BUFFER, _vertexBufferObject);
	glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW);
	glBindBuffer(GL_ARRAY_BUFFER, 0);
    
	glGenBuffers(1, &indexBufferObject);
    
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBufferObject);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indexData), indexData, GL_STATIC_DRAW);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
    printOpenGLError();
    
    
    // Vertex array objects
    glGenVertexArrays(1, &_vertexArrayObject);
    glBindVertexArray(_vertexArrayObject);
    
    size_t colorDataOffset = sizeof(float) * 3 * numberOfVertices;
    
    glBindBuffer(GL_ARRAY_BUFFER, _vertexBufferObject);
    glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
    glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 0, (void*)colorDataOffset);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBufferObject);
    
    glBindVertexArray(0);
    printOpenGLError();
    
    // Enable cull facing
    glEnable(GL_CULL_FACE);
    glCullFace(GL_BACK);
    glFrontFace(GL_CW);
    printOpenGLError();
    
    // Enable depth testing
    glEnable(GL_DEPTH_TEST);
	glDepthMask(GL_TRUE);
	glDepthFunc(GL_LEQUAL);
	glDepthRange(0.0f, 1.0f);
}
示例#19
0
GLFWwindow* gfx::GraphicsEngine::Initialize( int width, int height, bool vsync, bool fullscreen ){
	m_Width = width;
	m_Height = height;
	
	if( !glfwInit( ) )
		return nullptr;
	//glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
	//glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
	//glfwWindowHint(GLFW_DECORATED, GL_FALSE);
	if(fullscreen){
		m_Window = glfwCreateWindow( width, height, "ModelViewer", glfwGetPrimaryMonitor( ), nullptr );
	}else{
		m_Window = glfwCreateWindow( width, height, "ModelViewer", nullptr, nullptr );
	}
	if(!m_Window)
		return nullptr;

	glfwMakeContextCurrent( m_Window );
	ImGui_ImplGlfwGL3_Init( m_Window, true );
	glewExperimental = GL_TRUE;
	glewInit( );
	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LESS);
	glEnable(GL_CULL_FACE);
	glCullFace(GL_BACK);
	glFrontFace(GL_CCW);
	glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
	

	if(vsync){
		glfwSwapInterval( 1 );
	}else{
		glfwSwapInterval( 0 );
	}
	glClearColor(0.2f, 0.2f, 0.2f, 1.0f);
	//set camera
	float aspectRatio = width / (float)height;
	m_Camera.GetEditableLens( ).Near = 0.1f;
	m_Camera.GetEditableLens( ).Far = 100.0f;
	m_Camera.GetEditableLens( ).VerticalFOV = ( ( 90.0f / ( aspectRatio ) ) / 360.0f ) * 2 * glm::pi<float>( ); // calc FOV as horisontal FOV 90 degrees
	m_Camera.GetEditableLens().WindowHeight = height - BUTTON_SIZE * 2;
	m_Camera.GetEditableLens().WindowWidth = (int)(width * 0.5f);
	m_Camera.SetPosition(glm::vec3(0.0f, 10.0f, 20.0f));

	m_Camera.CalculateViewProjection();
	//load shaders
	m_Shader = g_ShaderBank.LoadShaderProgram( "shader/CombinedShader.glsl" );
	m_SpriteShader = g_ShaderBank.LoadShaderProgram("shader/SpriteShader.glsl");
	m_GizmoProgram = g_ShaderBank.LoadShaderProgram("shader/GizmoProgram.glsl");
	m_LineProgram = g_ShaderBank.LoadShaderProgram("shader/LineShader.glsl");
	//Load cubeTex
	m_SkyTex = new Texture();
	m_SkyTex->Init("asset/CubeMaps/square.dds", TEXTURE_CUBE);
	m_IrradianceTex = new Texture();
	m_IrradianceTex->Init("asset/CubeMaps/square_irr.dds", TEXTURE_CUBE);

	m_FrameBuffer.Init();

	glGenBuffers(1, &m_LineVBO);
	glGenVertexArrays(1, &m_LineVAO);
	glBindVertexArray(m_LineVAO);
	glBindBuffer(GL_ARRAY_BUFFER, m_LineVBO);
	glEnableVertexAttribArray(0);
	glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0);
	glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec2) * 100000, nullptr, GL_DYNAMIC_DRAW); //allocate buffer

	return m_Window;
}
示例#20
0
void Cone::initializeConeBottom()
{
	float angleStep = 2.0f * M_PI / slices;

	// vector containers to hold  data
	vector<pntVertexData> v; // vertex positions
	vector<unsigned int> indices; // indices
	GLuint VBO, IBO; // Identifiers for buffer objects
	
	GLuint currentIndex = 0;

    vec3 n = vec3(0.0f,0.0f,-1.0f);
	vec3 ctr = vec3( 0.0f, 0.0f, 0.0f );

	float theta = 0.0f;

    for (int j = slices; j >= 0; j--) {			

		theta = j * angleStep;
		vec3 v0 = vec3( cos( theta ) * base, sin( theta ) * base, 0.0f);
		v.push_back( pntVertexData( v0, n, getPlanarTextCoords( v0, base, height )));
		indices.push_back(currentIndex++);

		theta = (j-1)* angleStep;

		vec3 v1 = vec3( cos( theta ) * base, sin( theta ) * base, 0.0f);
		v.push_back( pntVertexData( v1, n, getPlanarTextCoords( v1, base, height )));
		indices.push_back(currentIndex++);

		v.push_back( pntVertexData( ctr, n, getPlanarTextCoords( ctr, base, height )));
		indices.push_back(currentIndex++);
	}

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

	// Create the buffer to hold interleaved data and bind the data to them
	glGenBuffers(1, &VBO);
	glBindBuffer(GL_ARRAY_BUFFER, VBO); // Buffer for vertex data
	glBufferData(GL_ARRAY_BUFFER, v.size() * sizeof(pntVertexData), &v[0], GL_STATIC_DRAW); //Buffering vertex data

	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(pntVertexData), 0);
	glEnableVertexAttribArray(0);

	glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(pntVertexData), (const GLvoid*)sizeof(vec3) );
	glEnableVertexAttribArray(1);

	glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, sizeof(pntVertexData), (const GLvoid*)(2 * sizeof(vec3)) );
	glEnableVertexAttribArray(3);

	// Generate a buffer for the indices
	glGenBuffers(1, &IBO);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), &indices[0] , GL_STATIC_DRAW);

	// store the number of indices for later use
	bottomIndicesCount = indices.size();
 
	v.clear();
	indices.clear();

} // end initializeConeBottom
/*
*	\brief Create the mesh
*/
void Mesh::Create( 
		Vertex *vertices,								//! A pointer to an array of verticies
		const int noofVerticies,						//! The number of verticies in the above array
		unsigned int *elements,							//! A pointer to an array of elements
		const int noofElements							//! The number of elements in the above array
	)
{
	// verticies
	glGenVertexArrays(1, &m_vao);
	glBindVertexArray(m_vao);
	glGenBuffers(1, &m_vertexVBO);
	glBindBuffer(GL_ARRAY_BUFFER, m_vertexVBO);
	glBufferData(
		GL_ARRAY_BUFFER,
		noofVerticies * sizeof(Vertex),
		vertices,
		GL_STATIC_DRAW
		);
	m_vertexCount = noofVerticies;

	// positon
	glEnableVertexAttribArray(0);
	glVertexAttribPointer(
		0, 
		3, 
		GL_FLOAT, 
		GL_FALSE,
		sizeof(Vertex), 
		TGL_BUFFER_OFFSET(0)
		);

	// normal
	glEnableVertexAttribArray(1);
	glVertexAttribPointer(
		1, 
		3, 
		GL_FLOAT, 
		GL_FALSE,
		sizeof(Vertex), 
		TGL_BUFFER_OFFSET(3 * sizeof(float))
		);

	// tangents
	glEnableVertexAttribArray(2);
	glVertexAttribPointer(
		2, 
		3, 
		GL_FLOAT, 
		GL_FALSE,
		sizeof(Vertex), 
		TGL_BUFFER_OFFSET(6 * sizeof(float))
		);

	// tex-coords
	glEnableVertexAttribArray(3);
	glVertexAttribPointer(
		3, 
		2, 
		GL_FLOAT, 
		GL_FALSE,
		sizeof(Vertex), 
		TGL_BUFFER_OFFSET(9 * sizeof(float))
		);

	// elements
	glGenBuffers(1, &m_elementVBO);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_elementVBO);
	glBufferData(
		GL_ELEMENT_ARRAY_BUFFER,
		noofElements * sizeof(unsigned int),
		elements,
		GL_STATIC_DRAW
		);

	m_elementCount = noofElements;
}
示例#22
0
void Cone::initializeConeBody()
{
    // Step in z and radius as stacks are drawn.
    double z0,z1;
	double r0, r1;

	const float angleStep = 2.0f * M_PI / slices;
	const float zStep = height / ( ( stacks > 0 ) ? stacks : 1 );
    const float rStep = base / ( ( stacks > 0 ) ? stacks : 1 );

	// Scaling factors for vertex normals 
    const float cosn = ( height / sqrt ( height * height + base * base ));
    const float sinn = ( base   / sqrt ( height * height + base * base ));

	// vector containers to hold  data
	vector<pntVertexData> v; // vertex positions
	vector<unsigned int> indices; // indices
	GLuint VBO, IBO; // Identifiers for buffer objects

	// Do the stacks
	z0 = 0.0;
    z1 = zStep;

    r0 = base;
    r1 = r0 - rStep;

	GLuint currentIndex = 0;

	float theta = 0.0f;

	for( int i = 0; i < stacks-1; i++ )
    {
        for( int j=0; j < slices; j++)
        {
			theta = j* angleStep;

            vec3 n01 = vec3(cos(theta) * cosn, sin(theta)*cosn, sinn);

            vec3 v0 = vec3(cos(theta) * r0,   sin(theta)*r0,   z0  );
			v.push_back( pntVertexData( v0, n01, getPlanarTextCoords( v0, base, height  )) ); // 0
            
			vec3 v1 = vec3(cos(theta) * r1,   sin(theta)*r1,   z1  );
			v.push_back( pntVertexData( v1, n01, getPlanarTextCoords( v1, base, height )) ); // 1

			theta = (j+1)* angleStep;
			vec3 n23 = vec3(cos(theta) * cosn, sin(theta) * cosn, sinn);

            vec3 v2 = vec3(cos(theta) * r0,   sin(theta) * r0,   z0  );
			v.push_back( pntVertexData( v2, n23, getPlanarTextCoords( v2, base, height )) ); // 2
           
			vec3 v3 = vec3(cos(theta) * r1,   sin(theta) * r1,  z1  );
			v.push_back( pntVertexData( v3, n23, getPlanarTextCoords( v3, base, height )) ); // 3

			indices.push_back(currentIndex);
			indices.push_back(currentIndex + 2);
			indices.push_back(currentIndex + 3);

			indices.push_back(currentIndex);
			indices.push_back(currentIndex + 3);
			indices.push_back(currentIndex + 1);

			currentIndex += 4;
        }

        z0 = z1; 
		z1 += zStep;
        r0 = r1; 
		r1 -= rStep;
    }

	vec3 n = vec3(cos(0.0)*cosn, sin(0.0)*cosn, sinn);


	for (int j=0; j < slices; j++)
	{
		theta = j* angleStep;

		vec3 v0 = vec3( cos(theta) * r0, sin(theta) * r0, z0 );
		v.push_back( pntVertexData( v0, n, getPlanarTextCoords( v0, base, height )) ); // 0
		
		vec3 v1 = vec3( 0, 0, height);
		v.push_back( pntVertexData( v1, n, getPlanarTextCoords( v1, base, height )) ); // 1

		theta = (j+1)* angleStep;

		n = vec3 ( cos(theta) * cosn, sin(theta) * cosn, sinn );
		vec3 v2 = vec3( cos(theta) * r0, sin(theta)*r0, z0 );
		v.push_back( pntVertexData( v2, n, getPlanarTextCoords( v2, base, height )) ); // 2

		indices.push_back(currentIndex);
		indices.push_back(currentIndex + 2);
		indices.push_back(currentIndex + 1);
		currentIndex += 3;
	}

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

	// Create the buffer to hold interleaved data and bind the data to them
	glGenBuffers(1, &VBO);
	glBindBuffer(GL_ARRAY_BUFFER, VBO); // Buffer for vertex data
	glBufferData(GL_ARRAY_BUFFER, v.size() * sizeof(pntVertexData), &v[0], GL_STATIC_DRAW); //Buffering vertex data

	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(pntVertexData), 0);
	glEnableVertexAttribArray(0);

	glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(pntVertexData), (const GLvoid*)sizeof(vec3) );
	glEnableVertexAttribArray(1);

	glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, sizeof(pntVertexData), (const GLvoid*)(2 * sizeof(vec3)) );
	glEnableVertexAttribArray(3);

	// Generate a buffer for the indices
	glGenBuffers(1, &IBO);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), &indices[0] , GL_STATIC_DRAW);

	// store the number of indices for later use
	bodyIndicesCount = indices.size();
 
	v.clear();
	indices.clear();

} // end
示例#23
0
int
drawTextures(EGLContextType *context, GLenum target, GLuint *textureIds, int texCount)
{
    unsigned int i;
    static int rectSize1 = MAX_RECT_SIZE;
    static int rectSize2 = MIN_RECT_SIZE;
    static int direction = 1;
    const GLfloat positions[4][2] = {
        { -rectSize1/100.f, -rectSize1/100.f},
        {  rectSize2/100.f, -rectSize2/100.f},
        {  rectSize1/100.f,  rectSize1/100.f},
        { -rectSize2/100.f,  rectSize2/100.f}
    };
    static const GLfloat texcoords[4][2] = {
        {  0.0f,  1.0f },
        {  1.0f,  1.0f },
        {  1.0f,  0.0f },
        {  0.0f,  0.0f }
    };

    if (direction) {
        rectSize1--;
        rectSize2++;
    } else {
        rectSize1++;
        rectSize2--;
    }

    if (rectSize1 < 10 || rectSize2 > 100) {
        rectSize1 = 10;
        rectSize2 = 100;
        direction = 0;
    }
    if (rectSize1 > 100 || rectSize2 < 10) {
        rectSize1 = 100;
        rectSize2 = 10;
        direction = 1;
    }


    if (!context)
        return -1;
    GLProgram *glProgram = context->glProgram;

    ASSERT(texCount == glProgram->texCount);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glUseProgram(glProgram->program);
    // glUniformMatrix4fv(program->proj_uniform, 1, GL_FALSE, egl->proj);
    glEnableVertexAttribArray(glProgram->attrPosition);
    glVertexAttribPointer(glProgram->attrPosition, 2, GL_FLOAT, GL_FALSE, 0, positions);
    glEnableVertexAttribArray(glProgram->attrTexCoord);
    glVertexAttribPointer(glProgram->attrTexCoord, 2, GL_FLOAT, GL_FALSE, 0, texcoords);

    for (i = 0; i < glProgram->texCount; i++) {
        glActiveTexture(GL_TEXTURE0 + i);
        glBindTexture(target, textureIds[i]);
        glUniform1i(glProgram->uniformTex[i], i);
    }
    glDrawArrays(GL_TRIANGLE_FAN, 0, 4);

    glDisableVertexAttribArray(1);
    glDisableVertexAttribArray(0);
    glUseProgram(0);

    eglSwapBuffers(context->eglContext.display, context->eglContext.surface);
    int glError = glGetError();
    if (glError != GL_NO_ERROR)
        return glError;

    return 0;
}
示例#24
0
int main()
{
	//窗口管理,初始化和设置
	glfwInit();
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);//OpenGL 使用核心模式
	glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);//窗口大小不可变

											 //创建一个窗口
	GLFWwindow* window = glfwCreateWindow(800, 600, "HelloWindow", nullptr, nullptr);
	if (window == nullptr)
	{
		std::cout << "failed to create window" << std::endl;
		glfwTerminate();
		return -1;
	}
	//设置上下文
	glfwMakeContextCurrent(window);

	//可以在创建窗口之后和游戏循环之前注册各种回调函数
	glfwSetKeyCallback(window, key_callback);

	//glew用来管理OpenGL的函数指针
	glewExperimental = GL_TRUE; //设置为true是为了让GLEW在管理OpenGL的函数指针时更多地使用现代化技术,设置为false,
	if (glewInit() != GLEW_OK)
	{
		std::cout << "failed to init glew!" << std::endl;
		return -1;
	}
	glViewport(0, 0, 800, 600);


	//shader 
	GLuint programID = shader::LoadShaders("v.s", "f.s");
	//设置顶点数据,位置,颜色,法向等属性
	GLfloat vertices[] = {
		0.5f,0.5f,0.0f,//右上角
		0.5f,-0.5f,0.0f,//右下角
		-0.5f,-0.5f,0.0f,//左下角
		-0.5f,0.5f,0.0f//左上角
	};
	GLuint indices[] = {//起始于0
		0,1,3,//第一个三角形
		1,2,3//第二个三角形
	};

	GLuint VBO, VAO, EBO;

	glGenVertexArrays(1, &VAO);
	glGenBuffers(1, &VBO);
	glGenBuffers(1, &EBO);
	//1.先绑定顶点数组对象(VAO),然后绑定顶点缓存对象(VBO)和属性指针(attribute pointer)
	glBindVertexArray(VAO);
	//2.绑定VBO
	glBindBuffer(GL_ARRAY_BUFFER, VBO);
	glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
	//3.绑定EBO
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
	//4. 设置顶点属性
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
	glEnableVertexAttribArray(0);

	//在使用glVertexAttribPointer之后,VBO就是当前上下文绑定对象,所以现在我们可以进行解绑操作
	glBindBuffer(GL_ARRAY_BUFFER, 0);
	//5. 解绑VAO,用完VAO之后解绑是一个好的习惯
	glBindVertexArray(0);

	//没有while循环的时候窗口闪关,while循环也称游戏循环,在GLFW退出之前一直保持运行
	while (!glfwWindowShouldClose(window))
	{
		//检查有没有触发什么事件,如:鼠标移动,调用相应回调函数
		glfwPollEvents();

		//glClearColor是状态设置函数,设置要清空缓冲的颜色
		glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
		//glClear是状态应用函数,整个指定清空的缓冲区都被填充glClearColor所设置的颜色
		glClear(GL_COLOR_BUFFER_BIT);

		//画三角形
		glUseProgram(programID);
		glBindVertexArray(VAO);	
		//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);//线框模式										 
		//glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); //填充模式
		glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
		glBindVertexArray(0);

		//交换缓冲区(储存着GLFW窗口每一个像素颜色的缓冲区)
		glfwSwapBuffers(window);
	}
	//循环结束后,释放所有资源
	glDeleteVertexArrays(1, &VAO);
	glDeleteBuffers(1, &VBO);


	glfwTerminate(); //释放GLFW分配的内存
	return 0;
}
示例#25
0
文件: main.cpp 项目: pierrereuter/agp
void display()
{
	// simulation
	if(runSimulation)
	{
		float *deviceVboPtr;
		int *deviceIboPtr;
		size_t num_bytes;

		cudaGraphicsMapResources(1, &cuVboResource, 0);
		cudaGraphicsMapResources(1, &cuIboResource, 0);
		cudaGraphicsResourceGetMappedPointer((void **)&deviceVboPtr, &num_bytes, cuVboResource);
		cudaGraphicsResourceGetMappedPointer((void **)&deviceIboPtr, &num_bytes, cuIboResource);

		launchParticleKernel(deviceVboPtr, deviceIboPtr, clothNumVertices, tTime, 0.1f, vertexSize, N, distance);

		cudaGraphicsUnmapResources(1, &cuVboResource, 0);
		cudaGraphicsUnmapResources(1, &cuIboResource, 0);
	}

	//
	mat4 viewM, projM, modelM;
	mat3 normalM;
	camera->getViewMatrix(viewM);
	camera->getProjMatrix(projM);
	modelM.setIdentity();
	normalM = viewM.topLeftCorner<3,3>();

	// TODO calc distance dependent point size
	vec3 eyeP;
	extractEyePosFromViewMatrix(viewM, eyeP);
	glPointSize(2.0f);

	// rendering
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	// draw cloth
	volcanoShaderProgram->bind();
	glUniformMatrix4fv(volcanoShaderProgram->uniform("view_matrix"), 1, false, viewM.data());
	glUniformMatrix4fv(volcanoShaderProgram->uniform("proj_matrix"), 1, false, projM.data());
	glUniformMatrix4fv(volcanoShaderProgram->uniform("model_matrix"), 1, false, modelM.data());
	glUniformMatrix3fv(volcanoShaderProgram->uniform("normal_matrix"), 1, false, normalM.data());
	glUniform1i(volcanoShaderProgram->uniform("bGlow"), 1);

	glBindBuffer(GL_ARRAY_BUFFER, clothVBO);
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 12 * sizeof(float), (void*)(0));
	glEnableVertexAttribArray(0);
	glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 12 * sizeof(float), (void*)(12));
	glEnableVertexAttribArray(1);
	glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, 12 * sizeof(float), (void*)(24));
	glEnableVertexAttribArray(2);
	glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, 12 * sizeof(float), (void*)(40));
	glEnableVertexAttribArray(3);
	glBindBuffer(GL_ARRAY_BUFFER, 0);

	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, clothIBO);
	glDrawElements(GL_TRIANGLES, clothNumTriangleindices, GL_UNSIGNED_INT, (void*)(0));
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

	glDisableVertexAttribArray(0);
	glDisableVertexAttribArray(1);
	glDisableVertexAttribArray(2);
	glDisableVertexAttribArray(3);
	volcanoShaderProgram->release();

	glutSwapBuffers();
}
bool DrawTextureScene::init(){
    if (!Layer::init()) {
        return false;
    }
    
    auto program = GLProgram::createWithFilenames("drawTextureVertexShader.vert", "drawTextureFragmentShader.frag");
    this->setGLProgram(program);
    
    glGenVertexArrays(1,&vao);
    glBindVertexArray(vao);
    typedef struct {
        float Position[2];
        float Color[4];
        float TexCoord[2];
    } Vertices;
    
    //纹理坐标的(0,0)点在图片的左上角,这个与OpenGL坐标系里左下角是(0,0)有所区别
    Vertices data[] =
    {
        { {-1,-1},{0,1,0,1},{0,1}},
        { {1,-1},{0,1,0,1},{1,1}},
        { {-1,1},{0,1,0,1},{0,0}},
        { {1,1},{0,1,0,1},{1,0}}
    };
    
    //纹理大小可根据Image得到,来设置渲染的顶点坐标
//    Vertices data[] =
//    {
//        { {-0.5,-0.5},{0,1,0,1},{0,1}},
//        { {0.5,-0.5},{0,1,0,1},{1,1}},
//        { {-0.5,0.5},{0,1,0,1},{0,0}},
//        { {0.5,0.5},{0,1,0,1},{1,0}}
//    };
    
    GLubyte indices[] = {0, 1, 2, 2, 3, 1};
    
    glGenBuffers(1, &vertexVBO);
    glBindBuffer(GL_ARRAY_BUFFER, vertexVBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(data), data, GL_STATIC_DRAW);
    
    GLuint positionLocation=glGetAttribLocation(program->getProgram(), "a_position");
    glEnableVertexAttribArray(positionLocation);
    glVertexAttribPointer(positionLocation,
                          2,
                          GL_FLOAT,
                          GL_FALSE,
                          sizeof(Vertices),
                          (GLvoid *)offsetof(Vertices, Position));
    
    GLuint colorLocation=glGetAttribLocation(program->getProgram(), "a_color");
    glEnableVertexAttribArray(colorLocation);
    glVertexAttribPointer(colorLocation,
                          4,
                          GL_FLOAT,
                          GL_FALSE,
                          sizeof(Vertices),
                          (GLvoid *)offsetof(Vertices, Color));
    
    GLuint textureLocation=glGetAttribLocation(program->getProgram(), "a_uvCoord");
    glEnableVertexAttribArray(textureLocation);
    glVertexAttribPointer(textureLocation,
                          2,
                          GL_FLOAT,
                          GL_FALSE,
                          sizeof(Vertices),
                          (GLvoid *)offsetof(Vertices, TexCoord));
    
    GLuint indexVBO;
    glGenBuffers(1, &indexVBO);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexVBO);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
    
    
    //method1
    Image* image=new Image();
    std::string imagePath = FileUtils::getInstance()->fullPathForFilename("HelloWorld.png");
    image->initWithImageFile(imagePath);
    
    
    glGenTextures(1, &textureID);
    glBindTexture(GL_TEXTURE_2D, textureID);
    
    //设置纹理在放大或者缩小的时候的插值方法(filter)以及在指定的纹理坐标超出(0-1)的范围的时候应该采用的策略
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,  GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    
    unsigned char* imageData = image->getData();
    int width = image->getWidth();
    int height = image->getHeight();
    glTexImage2D(GL_TEXTURE_2D,
                 0,
                 GL_RGB,
                 width,
                 height,
                 0,
                 GL_RGB,
                 GL_UNSIGNED_BYTE,//must be GL_UNSIGNED_BYTE
                 imageData);
    CC_SAFE_DELETE(image);
    
    /*
     //method2: the easier way
     Texture2D *texture = new Texture2D;
     texture->initWithImage(image);
     textureID = texture->getName();
     //method3: the easiest way
     Sprite *sprite = Sprite::create("HelloWorld.png");
     textureID = sprite->getTexture()->getName();
     */
    
    
    glBindVertexArray(0);
    glBindBuffer(GL_ARRAY_BUFFER, 0);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
    glBindTexture(GL_TEXTURE_2D, 0);
    
    
    return true;
}
示例#27
0
文件: Draw.c 项目: Kableado/GameLib
/////////////////////////////
// Draw_Init
//
// Initializes the game window.
int Draw_Init(int width, int height, char *title, int pfps, int fps) {

	// Set globals
	proc_t_frame = 1000000 / pfps;
	draw_t_frame = 1000000 / fps;
	_fps = fps;
	_width = width;
	_height = height;

	// Initialize SDL
	if (SDL_Init(SDL_INIT_VIDEO) < 0) {
		Print("Draw_Init: Failure initializing SDL.\n");
		Print("\tSDL Error: %s\n", SDL_GetError());
		return (0);
	}

	// Initialize video mode
	_screen = SDL_SetVideoMode(width, height, 32, SDL_HWSURFACE | SDL_OPENGL);
	if (_screen == NULL) {
		Print("Draw_Init: Failure initializing video mode.\n");
		Print("\tSDL Error: %s\n", SDL_GetError());
		return (0);
	}
	SDL_WM_SetCaption(title, NULL);
	Draw_ShowInfo();

#if USE_OpenGL
	// Set the desired state
	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
	glDisable(GL_CULL_FACE);
	glEnable(GL_TEXTURE_2D);
	glDisable(GL_LIGHTING);
	glDisable(GL_DEPTH_TEST);
	glDepthMask(GL_FALSE);

	// Triplebuffer swap
	glClear(GL_COLOR_BUFFER_BIT);
	SDL_GL_SwapBuffers();
	glClear(GL_COLOR_BUFFER_BIT);
	SDL_GL_SwapBuffers();
	glClear(GL_COLOR_BUFFER_BIT);
	SDL_GL_SwapBuffers();
	glClear(GL_COLOR_BUFFER_BIT);

	glEnableClientState(GL_COLOR_ARRAY);
	glEnableClientState(GL_TEXTURE_COORD_ARRAY);
	glEnableClientState(GL_VERTEX_ARRAY);

#endif

#if USE_OpenGLES

	const char vertexShaderSource[] = "attribute vec4 aPosition;       \n"
									  "attribute vec2 aTexCoord;       \n"
									  "attribute vec4 aColor;          \n"
									  "varying vec2 vTexCoord;         \n"
									  "varying vec4 vColor;            \n"
									  "uniform mat4 sProjectionMatrix; \n"
									  "void main() {                   \n"
									  "   gl_Position = aPosition *    \n"
									  "            sProjectionMatrix;  \n"
									  "   vTexCoord = aTexCoord;       \n"
									  "   vColor = aColor;             \n"
									  "}                               \n";

	const char fragmentShaderSource[] =
		"precision mediump float;                                \n"
		"varying vec2 vTexCoord;                                 \n"
		"varying vec4 vColor;                                    \n"
		"uniform sampler2D sTexture;                             \n"
		"void main() {                                           \n"
		"  gl_FragColor = texture2D(sTexture, vTexCoord)*vColor; \n"
		"}                                                       \n";

	programObject = Draw_BuildProgram(vertexShaderSource, fragmentShaderSource);
	glUseProgram(programObject);

	vertPosLoc = glGetAttribLocation(programObject, "aPosition");
	vertTexLoc = glGetAttribLocation(programObject, "aTexCoord");
	vertColorLoc = glGetAttribLocation(programObject, "aColor");

	textureLoc = glGetUniformLocation(programObject, "sTexture");
	projectionMatrixLoc =
		glGetUniformLocation(programObject, "sProjectionMatrix");

	glUniform1i(textureLoc, 0);

	glGenBuffers(1, &vertexObject);
	glBindBuffer(GL_ARRAY_BUFFER, vertexObject);
	glBufferData(GL_ARRAY_BUFFER,
				 Vertex2D_Length * sizeof(float) * Max_Vertices, NULL,
				 GL_DYNAMIC_DRAW);

	glBindBuffer(GL_ARRAY_BUFFER, vertexObject);

	glVertexAttribPointer(vertPosLoc, 2, GL_FLOAT, GL_FALSE,
						  Vertex2D_Length * sizeof(float),
						  (void *)(0 * sizeof(float)));
	glVertexAttribPointer(vertTexLoc, 2, GL_FLOAT, GL_FALSE,
						  Vertex2D_Length * sizeof(float),
						  (void *)(2 * sizeof(float)));
	glVertexAttribPointer(vertColorLoc, 4, GL_FLOAT, GL_FALSE,
						  Vertex2D_Length * sizeof(float),
						  (void *)(4 * sizeof(float)));

	glEnableVertexAttribArray(vertPosLoc);
	glEnableVertexAttribArray(vertTexLoc);
	glEnableVertexAttribArray(vertColorLoc);

	unsigned char whiteTexData[4] = {255, 255, 255, 255};
	_whiteTex = Draw_UploadGLTexture(1, 1, whiteTexData);

#endif

	// Set the proyection (2D)
	glViewport(0, 0, _width, _height);
	float projectionMatrix[16] = {1, 0, 0, 0, 0, 1, 0, 0,
								  0, 0, 1, 0, 0, 0, 0, 1};
	projectionMatrix[0] = (2.0f / _width);
	projectionMatrix[5] = -(2.0f / _height);
	projectionMatrix[10] = -0.001f;
	projectionMatrix[3] = -1.0f;
	projectionMatrix[7] = 1.0f;
	Draw_SetMatrix(projectionMatrix);

	// Enable Alpha blending
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	// Initialize the triangle array
	_quadArray = QuadArray2D_Create(400);

	Draw_SetColor(1.0f, 1.0f, 1.0f, 1.0f);

	return (1);
}
示例#28
0
void test_quad_textured(int shadow, int cfunc)
{
	GLint width, height;
	GLuint textures[2], texture_handle;
	GLfloat vVertices[] = {
			// front
			-0.45, -0.75, 0.0,
			 0.45, -0.75, 0.0,
			-0.45,  0.75, 0.0,
			 0.45,  0.75, 0.0
	};

	GLfloat vTexCoords[] = {
			1.0f, 1.0f,
			0.0f, 1.0f,
			1.0f, 0.0f,
			0.0f, 0.0f,
	};

	EGLSurface surface;

	RD_START("quad-textured", "shadow=%d, cfunc=%x", shadow, cfunc);

	display = get_display();

	/* get an appropriate EGL frame buffer configuration */
	ECHK(eglChooseConfig(display, config_attribute_list, &config, 1, &num_config));
	DEBUG_MSG("num_config: %d", num_config);

	/* create an EGL rendering context */
	ECHK(context = eglCreateContext(display, config, EGL_NO_CONTEXT, context_attribute_list));

	surface = make_window(display, config, 255, 255);

	ECHK(eglQuerySurface(display, surface, EGL_WIDTH, &width));
	ECHK(eglQuerySurface(display, surface, EGL_HEIGHT, &height));

	DEBUG_MSG("Buffer: %dx%d", width, height);

	/* connect the context to the surface */
	ECHK(eglMakeCurrent(display, surface, surface, context));

	printf("EGL Version %s\n", eglQueryString(display, EGL_VERSION));
	printf("EGL Vendor %s\n", eglQueryString(display, EGL_VENDOR));
	printf("EGL Extensions %s\n", eglQueryString(display, EGL_EXTENSIONS));
	printf("GL Version %s\n", glGetString(GL_VERSION));
	printf("GL extensions: %s\n", glGetString(GL_EXTENSIONS));

	program = get_program(vertex_shader_source, shadow ?
			fragment_shader_source_shadow : fragment_shader_source);

	GCHK(glBindAttribLocation(program, 0, "in_position"));
	GCHK(glBindAttribLocation(program, 1, "in_TexCoord"));

	link_program(program);

	GCHK(glViewport(0, 0, width, height));

	/* clear the color buffer */
	GCHK(glClearColor(0.5, 0.5, 0.5, 1.0));
	GCHK(glClear(GL_COLOR_BUFFER_BIT));

	GCHK(glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, vVertices));
	GCHK(glEnableVertexAttribArray(0));

	GCHK(glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, vTexCoords));
	GCHK(glEnableVertexAttribArray(1));

	GCHK(glGenTextures(2, &textures));

	GCHK(glActiveTexture(GL_TEXTURE0));
	GCHK(glBindTexture(GL_TEXTURE_2D, textures[0]));

	if (shadow) {
		GCHK(glTexImage2D(
				GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT,
				cube_texture.width/2, cube_texture.height/2, 0,
				GL_DEPTH_COMPONENT, GL_FLOAT, cube_texture.pixel_data));
	} else {
		GCHK(glTexImage2D(
				GL_TEXTURE_2D, 0, GL_RGB,
				cube_texture.width, cube_texture.height, 0,
				GL_RGB, GL_UNSIGNED_BYTE, cube_texture.pixel_data));
	}

	GCHK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST));
	GCHK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST));
	GCHK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE));
	GCHK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE));
	GCHK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE));

	if (shadow) {
#define GL_TEXTURE_COMPARE_MODE           0x884C
#define GL_TEXTURE_COMPARE_FUNC           0x884D
#define GL_COMPARE_REF_TO_TEXTURE         0x884E
		GCHK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE,
				GL_COMPARE_REF_TO_TEXTURE));
		GCHK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC,
				cfunc));
	} else {
		float minlod = cfunc, maxlod = cfunc;
		GCHK(glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_LOD, minlod));
		GCHK(glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_LOD, maxlod));
		switch (cfunc) {
		case 0:
			GCHK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST));
			break;
		case 1:
			GCHK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST));
			break;
		case 2:
			GCHK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST));
			break;
		case 3:
			GCHK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR));
			break;
		case 4:
			GCHK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR));
			break;
#ifndef GL_TEXTURE_MAX_ANISOTROPY_EXT
#define GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE
#endif
		case 5:
			GCHK(glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 4));
			break;
		case 6:
			GCHK(glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 8));
			break;
		case 7:
			GCHK(glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 16));
			break;
		case 8:
			GCHK(glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 32));
			break;
		case 9:
			GCHK(glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 320));
			break;
		}
	}

	GCHK(texture_handle = glGetUniformLocation(program, "uTexture"));
	GCHK(glUniform1i(texture_handle, 0)); /* '0' refers to texture unit 0. */

	GCHK(glActiveTexture(GL_TEXTURE1));
	GCHK(glBindTexture(GL_TEXTURE_2D, textures[1]));

	GCHK(glTexImage2D(
			GL_TEXTURE_2D, 0, GL_RGBA,
			cube_texture.width/3, cube_texture.height-1, 0,
			GL_RGBA, GL_UNSIGNED_BYTE, cube_texture.pixel_data+1));

	/* Note: cube turned black until these were defined. */
	GCHK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR));
	GCHK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR));
	GCHK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE));
	GCHK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE));
	GCHK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE));

	GCHK(texture_handle = glGetUniformLocation(program, "uTexture"));
	GCHK(glUniform1i(texture_handle, 1)); /* '1' refers to texture unit 1. */

	GCHK(glEnable(GL_CULL_FACE));

	GCHK(glDrawArrays(GL_TRIANGLE_STRIP, 0, 4));

	ECHK(eglSwapBuffers(display, surface));
	GCHK(glFlush());

	sleep(1);

	ECHK(eglDestroySurface(display, surface));

	ECHK(eglTerminate(display));

	RD_END();
}
示例#29
0
void DecalEngine::UpdateBuffers()
{
    if( !mDirty || mDecals.empty() )
    {
        return;
    }
    mDirty = false;
    size_t CurSize = mDecals.size();

    Vec2s_t Positions;
    Vec4s_t TexCoords;
    Floats_t Headings;
    Floats_t Radii;
    Floats_t Alphas;
    Positions.reserve( CurSize );
    Alphas.reserve( CurSize );
    TexCoords.reserve( CurSize );
    Headings.reserve( CurSize );
    Radii.reserve( CurSize );

    Decals_t::const_iterator i = mDecals.begin();
    mCounts = render::count(
                  boost::lambda::bind( &getNextTextId, boost::ref( i ), mDecals.end(),
                                       boost::ref( Positions ), boost::ref( Alphas ), boost::ref( TexCoords ),
                                       boost::ref( Headings ), boost::ref( Radii ),
                                       boost::lambda::_1 )
              );


    mVAO.Bind();

    if( CurSize != mPrevDecalsSize )
    {
        size_t TotalSize = CurSize * ( sizeof( glm::vec4 ) + sizeof( glm::vec2 ) + 3 * sizeof( GLfloat ) );
        glBufferData( GL_ARRAY_BUFFER, TotalSize, NULL, GL_DYNAMIC_DRAW );
        mPrevDecalsSize = CurSize;
    }

    size_t CurrentOffset = 0;
    size_t CurrentSize = 0;
    GLuint CurrentAttribIndex = 0;

    CurrentSize = CurSize * sizeof( glm::vec4 );
    glBufferSubData( GL_ARRAY_BUFFER, CurrentOffset, CurrentSize, &TexCoords[0] );
    glEnableVertexAttribArray( CurrentAttribIndex );
    mTexIndex = CurrentOffset;
    ++CurrentAttribIndex;
    CurrentOffset += CurrentSize;

    CurrentSize = CurSize * sizeof( glm::vec2 );
    glBufferSubData( GL_ARRAY_BUFFER, CurrentOffset, CurrentSize, &Positions[0] );
    glEnableVertexAttribArray( CurrentAttribIndex );
    mPosIndex = CurrentOffset;
    ++CurrentAttribIndex;
    CurrentOffset += CurrentSize;

    CurrentSize = CurSize * sizeof( GLfloat );
    glBufferSubData( GL_ARRAY_BUFFER, CurrentOffset, CurrentSize, &Headings[0] );
    glEnableVertexAttribArray( CurrentAttribIndex );
    mHeadingIndex = CurrentOffset;
    ++CurrentAttribIndex;
    CurrentOffset += CurrentSize;

    CurrentSize = CurSize * sizeof( GLfloat );
    glBufferSubData( GL_ARRAY_BUFFER, CurrentOffset, CurrentSize, &Alphas[0] );
    glEnableVertexAttribArray( CurrentAttribIndex );
    mAlphaIndex = CurrentOffset;
    ++CurrentAttribIndex;
    CurrentOffset += CurrentSize;

    CurrentSize = CurSize * sizeof( GLfloat );
    glBufferSubData( GL_ARRAY_BUFFER, CurrentOffset, CurrentSize, &Radii[0] );
    glEnableVertexAttribArray( CurrentAttribIndex );
    mRadiusIndex = CurrentOffset;
    ++CurrentAttribIndex;
    CurrentOffset += CurrentSize;

    mVAO.Unbind();
}
void object::load(const char * filename)
{
    FILE * infile = fopen(filename, "rb");
    size_t filesize;
    char * data;

    this->free();

    fseek(infile, 0, SEEK_END);
    filesize = ftell(infile);
    fseek(infile, 0, SEEK_SET);

    data = new char[filesize];

    fread(data, filesize, 1, infile);

    char * ptr = data;
    SB6M_HEADER * header = (SB6M_HEADER *)ptr;
    ptr += header->size;

    SB6M_VERTEX_ATTRIB_CHUNK * vertex_attrib_chunk = NULL;
    SB6M_CHUNK_VERTEX_DATA * vertex_data_chunk = NULL;
    SB6M_CHUNK_INDEX_DATA * index_data_chunk = NULL;
    SB6M_CHUNK_SUB_OBJECT_LIST * sub_object_chunk = NULL;

    unsigned int i;
    for (i = 0; i < header->num_chunks; i++)
    {
        SB6M_CHUNK_HEADER * chunk = (SB6M_CHUNK_HEADER *)ptr;
        ptr += chunk->size;
        switch (chunk->chunk_type)
        {
            case SB6M_CHUNK_TYPE_VERTEX_ATTRIBS:
                vertex_attrib_chunk = (SB6M_VERTEX_ATTRIB_CHUNK *)chunk;
                break;
            case SB6M_CHUNK_TYPE_VERTEX_DATA:
                vertex_data_chunk = (SB6M_CHUNK_VERTEX_DATA *)chunk;
                break;
            case SB6M_CHUNK_TYPE_INDEX_DATA:
                index_data_chunk = (SB6M_CHUNK_INDEX_DATA *)chunk;
                break;
            case SB6M_CHUNK_TYPE_SUB_OBJECT_LIST:
                sub_object_chunk = (SB6M_CHUNK_SUB_OBJECT_LIST *)chunk;
                break;
            default:
                break; // goto failed;
        }
    }

// failed:

    if (sub_object_chunk != NULL)
    {
        if (sub_object_chunk->count > MAX_SUB_OBJECTS)
        {
            sub_object_chunk->count = MAX_SUB_OBJECTS;
        }

        for (i = 0; i < sub_object_chunk->count; i++)
        {
            sub_object[i] = sub_object_chunk->sub_object[i];
        }

        num_sub_objects = sub_object_chunk->count;
    }
    else
    {
        sub_object[0].first = 0;
        sub_object[0].count = vertex_data_chunk->total_vertices;
        num_sub_objects = 1;
    }

    glGenBuffers(1, &vertex_buffer);
    glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer);
    glBufferData(GL_ARRAY_BUFFER, vertex_data_chunk->data_size, data + vertex_data_chunk->data_offset, GL_STATIC_DRAW);

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

    for (i = 0; i < vertex_attrib_chunk->attrib_count; i++)
    {
        SB6M_VERTEX_ATTRIB_DECL &attrib_decl = vertex_attrib_chunk->attrib_data[i];
        glVertexAttribPointer(i,
                              attrib_decl.size,
                              attrib_decl.type,
                              attrib_decl.flags & SB6M_VERTEX_ATTRIB_FLAG_NORMALIZED ? GL_TRUE : GL_FALSE,
                              attrib_decl.stride,
                              (GLvoid *)(uintptr_t)attrib_decl.data_offset);
        glEnableVertexAttribArray(i);
    }

    if (index_data_chunk != NULL)
    {
        glGenBuffers(1, &index_buffer);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, index_buffer);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER,
                     index_data_chunk->index_count * (index_data_chunk->index_type == GL_UNSIGNED_SHORT ? sizeof(GLushort) : sizeof(GLubyte)),
                     data + index_data_chunk->index_data_offset, GL_STATIC_DRAW);
        num_indices = index_data_chunk->index_count;
        index_type = index_data_chunk->index_type;
    }
    else
    {
        num_indices = vertex_data_chunk->total_vertices;
    }

    delete[] data;

    fclose(infile);

    glBindVertexArray(0);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}