Esempio n. 1
1
bool ImGui_ImplSdl_CreateDeviceObjects()
{
    // Backup GL state
    GLint last_texture, last_array_buffer;
    glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
    glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer);

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

    const GLchar* fragment_shader =
        // WebGL requires precision specifiers but OpenGL 2.1 disallows
        // them, so I define the shader without it and then add it here.
        "precision mediump float;\n"
        "uniform sampler2D Texture;\n"
        "varying vec2 Frag_UV;\n"
        "varying vec4 Frag_Color;\n"
        "void main()\n"
        "{\n"
        "	gl_FragColor = Frag_Color * texture2D(Texture, Frag_UV);\n"
        "}\n";

    g_ShaderHandle = glCreateProgram();
    g_VertHandle = glCreateShader(GL_VERTEX_SHADER);
    g_FragHandle = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(g_VertHandle, 1, &vertex_shader, 0);
    glShaderSource(g_FragHandle, 1, &fragment_shader, 0);
    glCompileShader(g_VertHandle);
    glCompileShader(g_FragHandle);
    glAttachShader(g_ShaderHandle, g_VertHandle);
    glAttachShader(g_ShaderHandle, g_FragHandle);
    glLinkProgram(g_ShaderHandle);
    
    g_AttribLocationTex = glGetUniformLocation(g_ShaderHandle, "Texture");
    g_AttribLocationProjMtx = glGetUniformLocation(g_ShaderHandle, "ProjMtx");
    g_AttribLocationPosition = glGetAttribLocation(g_ShaderHandle, "Position");
    g_AttribLocationUV = glGetAttribLocation(g_ShaderHandle, "UV");
    g_AttribLocationColor = glGetAttribLocation(g_ShaderHandle, "Color");

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

    ImGuiIO& io = ImGui::GetIO();

    // Build texture
    unsigned char* pixels;
    int width, height;
    io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);   // Load as RGBA 32-bits for OpenGL3 demo because it is more likely to be compatible with user's existing shader.

    // Create OpenGL texture
    glGenTextures(1, &g_FontTexture);
    glBindTexture(GL_TEXTURE_2D, g_FontTexture);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);

    // Store our identifier
    io.Fonts->TexID = (void *)(intptr_t)g_FontTexture;

    // Cleanup (don't clear the input data if you want to append new fonts later)
    io.Fonts->ClearInputData();
    io.Fonts->ClearTexData();

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

    return true;
}
Esempio n. 2
0
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// HW3a::initShader1:
//
// Initialize vertex and fragment shaders for texture mapping.
//
void
HW3a::initShader1()
{
	// compile vertex shader
    if(!m_program[0].addShaderFromSourceFile(QGLShader::Vertex, ":/vshader3a1.glsl")) {
		QMessageBox::critical(0, "Error", "Vertex shader error", QMessageBox::Ok); 
		QApplication::quit();
	}

	// compile fragment shader
    if(!m_program[0].addShaderFromSourceFile(QGLShader::Fragment, ":/fshader3a1.glsl")) {
		QMessageBox::critical(0, "Error", "Fragment shader error",QMessageBox::Ok); 
		QApplication::quit();
	}

	// bind the attribute variable in the glsl program with a generic vertex attribute index;
	// values provided via ATTRIB_VERTEX will modify the value of "a_position")
	glBindAttribLocation(m_program[0].programId(), ATTRIB_VERTEX, "a_Position");

	// bind the attribute variable in the glsl program with a generic vertex attribute index;
	// values provided via ATTRIB_TEXTURE_POSITION will modify the value of "a_TexCoord")
	glBindAttribLocation(m_program[0].programId(), ATTRIB_TEXTURE_POSITION, "a_TexCoord");

	// link shader pipeline; attribute bindings go into effect at this point
	if(!m_program[0].link()) {
		QMessageBox::critical(0, "Error", "Could not link shader", QMessageBox::Ok); 
		QApplication::quit();
	}

	// get storage location of u_ModelMatrix in vertex shader
	m_uniform[0][MV] = glGetUniformLocation(m_program[0].programId(), "u_ModelMatrix");
	if((int) m_uniform[0][MV] < 0) {
		qDebug() << "Failed to get the storage location of u_ModelMatrix";
		exit(-1);
	}

	// get storage location of u_Theta in vertex shader
	m_uniform[0][THETA] = glGetUniformLocation(m_program[0].programId(), "u_Theta");
	if((int) m_uniform[0][THETA] < 0) {
		qDebug() << "Failed to get the storage location of u_Theta";
		exit(-1);
	}

	// get storage location of u_Twist in vertex shader
	m_uniform[0][TWIST] = glGetUniformLocation(m_program[0].programId(), "u_Twist");
	if((int) m_uniform[0][TWIST] < 0) {
		qDebug() << "Failed to get the storage location of u_Twist";
		exit(-1);
	}

	// get storage location of u_Sampler in fragment shader
    m_uniform[0][SAMPLER] = glGetUniformLocation(m_program[0].programId(), "u_Sampler");
    if((int) m_uniform[0][SAMPLER] < 0) {
        qDebug() << "Failed to get the storage location of u_Sampler";
        exit(-1);
    }

	// bind the glsl program
	glUseProgram(m_program[0].programId());

	// init model matrix; pass it to vertex shader along with theta and twist flag
	m_ModelMatrix.setToIdentity();
	glUniformMatrix4fv(m_uniform[0][MV], 1, GL_FALSE, m_ModelMatrix.constData());
	glUniform1f(m_uniform[0][THETA], m_theta);
	glUniform1i(m_uniform[0][TWIST], m_twist);
    glUniform1i(m_uniform[0][SAMPLER], 0);
}
Esempio n. 3
0
void Object3D::setShaderProgram(const char *vertexShader, const char *fragmentShader){
	GLuint vsSource, fsSource;
	vsSource = glCreateShader(GL_VERTEX_SHADER);
	fsSource = glCreateShader(GL_FRAGMENT_SHADER);

	glShaderSource(fsSource, 1, &fragmentShader, 0);
	glShaderSource(vsSource, 1, &vertexShader, 0);

	glCompileShader(vsSource);
	glCompileShader(fsSource);

	GLint success = 0;

	glGetShaderiv(fsSource, GL_COMPILE_STATUS, &success);
	if (!success){
		GLint maxLength = 0;
		glGetShaderiv(fsSource, GL_INFO_LOG_LENGTH, &maxLength);

		std::vector<GLchar> infolog(maxLength);
		glGetShaderInfoLog(fsSource, maxLength, &maxLength, &infolog[0]);
		std::cout << infolog.data() << std::endl;

		return;
	}

	success = 0;
	glGetShaderiv(vsSource, GL_COMPILE_STATUS, &success);
	if (!success){
		GLint maxLength = 0;
		glGetShaderiv(vsSource, GL_INFO_LOG_LENGTH, &maxLength);

		std::vector<GLchar> infolog(maxLength);
		glGetShaderInfoLog(vsSource, maxLength, &maxLength, &infolog[0]);
		std::cout << infolog.data() << std::endl;

		return;
	}

	shaderProgram = glCreateProgram();
	glAttachShader(shaderProgram, vsSource);
	glAttachShader(shaderProgram, fsSource);

	glLinkProgram(shaderProgram);
	glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
	if (success == GL_FALSE){
		GLint maxLength = 0;
		glGetProgramiv(shaderProgram, GL_INFO_LOG_LENGTH, &maxLength);

		std::vector<GLchar> infolog(maxLength);
		glGetProgramInfoLog(shaderProgram, maxLength, &maxLength, &infolog[0]);
		std::cout << infolog.data() << std::endl;
		return;
	}

	glDetachShader(shaderProgram, vsSource);
	glDetachShader(shaderProgram, fsSource);


	attributeUV = glGetAttribLocation(shaderProgram, "vertexUV");
	attributeTex = glGetUniformLocation(shaderProgram, "textureSampler");

	hasShaderProgram = true;
	if (attributeUV == -1){
		std::cout << "UV not bound. " << std::endl;
		hasShaderProgram = false;
	}
	if (attributeTex == -1){
		std::cout << "Texture not bound. " << std::endl;
		hasShaderProgram = false;
	}
}
int main () {
	/*--------------------------------START OPENGL---------------------------*/
	assert (restart_gl_log ());
	// start GL context and O/S window using the GLFW helper library
	assert (start_gl ());
	glEnable (GL_DEPTH_TEST); // enable depth-testing
    // depth-testing interprets a smaller value as "closer"
	glDepthFunc (GL_LESS);
    glEnable (GL_CULL_FACE); // cull face
	glCullFace (GL_BACK); // cull back face
    // set counter-clock-wise vertex order to mean the front
	glFrontFace (GL_CCW);
    glClearColor (0.2, 0.2, 0.2, 1.0); // grey background to help spot mistakes
	glViewport (0, 0, g_gl_width, g_gl_height);
	
/*------------------------------CREATE GEOMETRY------------------------------*/
	GLfloat* vp = NULL; // array of vertex points
	GLfloat* vn = NULL; // array of vertex normals
	GLfloat* vt = NULL; // array of texture coordinates
	int g_point_count = 0;
	assert (load_obj_file (MESH_FILE, vp, vt, vn, g_point_count));

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

	GLuint points_vbo;
	if (NULL != vp) {
		glGenBuffers (1, &points_vbo);
		glBindBuffer (GL_ARRAY_BUFFER, points_vbo);
		glBufferData (GL_ARRAY_BUFFER, 3 * g_point_count * sizeof (GLfloat),
                      vp, GL_STATIC_DRAW);
		glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, 0, NULL);
		glEnableVertexAttribArray (0);
	}
	GLuint normals_vbo;
	if (NULL != vn) {
		glGenBuffers (1, &normals_vbo);
		glBindBuffer (GL_ARRAY_BUFFER, normals_vbo);
		glBufferData (GL_ARRAY_BUFFER, 3 * g_point_count * sizeof (GLfloat),
                      vn, GL_STATIC_DRAW);
		glVertexAttribPointer (1, 3, GL_FLOAT, GL_FALSE, 0, NULL);
		glEnableVertexAttribArray (1);
	}
	GLuint texcoords_vbo;
	if (NULL != vp) {
		glGenBuffers (1, &texcoords_vbo);
		glBindBuffer (GL_ARRAY_BUFFER, texcoords_vbo);
		glBufferData (GL_ARRAY_BUFFER, 2 * g_point_count * sizeof (GLfloat),
                      vp, GL_STATIC_DRAW);
		glVertexAttribPointer (2, 2, GL_FLOAT, GL_FALSE, 0, NULL);
		glEnableVertexAttribArray (2);
	}
	
/*-------------------------------CREATE SHADERS------------------------------*/
	GLuint shader_programme = create_programme_from_files (VERTEX_SHADER_FILE,
		FRAGMENT_SHADER_FILE);
	int view_mat_location = glGetUniformLocation (shader_programme, "view");
	int proj_mat_location = glGetUniformLocation (shader_programme, "proj");
	
	/* if converting to GLSL 410 do this to replace GLSL texture bindings:
	GLint diffuse_map_loc, specular_map_loc, ambient_map_loc, emission_map_loc;
	diffuse_map_loc = glGetUniformLocation (shader_programme, "diffuse_map");
	specular_map_loc = glGetUniformLocation (shader_programme, "specular_map");
	ambient_map_loc = glGetUniformLocation (shader_programme, "ambient_map");
	emission_map_loc = glGetUniformLocation (shader_programme, "emission_map");
	assert (diffuse_map_loc > -1);
	assert (specular_map_loc > -1);
	assert (ambient_map_loc > -1);
	assert (emission_map_loc > -1);
	glUseProgram (shader_programme);
	glUniform1i (diffuse_map_loc, 0);
	glUniform1i (specular_map_loc, 1);
	glUniform1i (ambient_map_loc, 2);
	glUniform1i (emission_map_loc, 3);
	*/
	
	// load texture
	GLuint tex_diff, tex_spec, tex_amb, tex_emiss;
	glActiveTexture (GL_TEXTURE0);
	assert (load_texture ("boulder_diff.png", &tex_diff));
	glActiveTexture (GL_TEXTURE1);
	assert (load_texture ("boulder_spec.png", &tex_spec));
	glActiveTexture (GL_TEXTURE2);
	assert (load_texture ("ao.png", &tex_amb));
	glActiveTexture (GL_TEXTURE3);
	assert (load_texture ("tileable9b_emiss.png", &tex_emiss));
	
	#define ONE_DEG_IN_RAD (2.0 * M_PI) / 360.0 // 0.017444444
	// input variables
	float near = 0.1f; // clipping plane
	float far = 100.0f; // clipping plane
	float fov = 67.0f * ONE_DEG_IN_RAD; // convert 67 degrees to radians
	float aspect = (float)g_gl_width / (float)g_gl_height; // aspect ratio
	// matrix components
	float range = tan (fov * 0.5f) * near;
	float Sx = (2.0f * near) / (range * aspect + range * aspect);
	float Sy = near / range;
	float Sz = -(far + near) / (far - near);
	float Pz = -(2.0f * far * near) / (far - near);
	GLfloat proj_mat[] = {
		Sx, 0.0f, 0.0f, 0.0f,
		0.0f, Sy, 0.0f, 0.0f,
		0.0f, 0.0f, Sz, -1.0f,
		0.0f, 0.0f, Pz, 0.0f
	};
	
		
	float cam_speed = 1.0f; // 1 unit per second
	float cam_yaw_speed = 10.0f; // 10 degrees per second
    // don't start at zero, or we will be too close
	float cam_pos[] = {0.0f, 0.0f, 5.0f};
	float cam_yaw = 0.0f; // y-rotation in degrees
	mat4 T = translate (identity_mat4 (), vec3 (-cam_pos[0], -cam_pos[1],
                                                -cam_pos[2]));
	mat4 R = rotate_y_deg (identity_mat4 (), -cam_yaw);
	mat4 view_mat = R * T;
	
	glUseProgram (shader_programme);
	glUniformMatrix4fv (view_mat_location, 1, GL_FALSE, view_mat.m);
	glUniformMatrix4fv (proj_mat_location, 1, GL_FALSE, proj_mat);
	
	while (!glfwWindowShouldClose (g_window)) {
		static double previous_seconds = glfwGetTime ();
		double current_seconds = glfwGetTime ();
		double elapsed_seconds = current_seconds - previous_seconds;
		previous_seconds = current_seconds;
	
		_update_fps_counter (g_window);
		// wipe the drawing surface clear
		glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		glViewport (0, 0, g_gl_width, g_gl_height);
		
		glUseProgram (shader_programme);
		glBindVertexArray (vao);
		// draw points 0-3 from the currently bound VAO with current shader
		glDrawArrays (GL_TRIANGLES, 0, g_point_count);
		// update other events like input handling 
		glfwPollEvents ();
		
		// control keys
		bool cam_moved = false;
		if (glfwGetKey (g_window, GLFW_KEY_A)) {
			cam_pos[0] -= cam_speed * elapsed_seconds;
			cam_moved = true;
		}
		if (glfwGetKey (g_window, GLFW_KEY_D)) {
			cam_pos[0] += cam_speed * elapsed_seconds;
			cam_moved = true;
		}
		if (glfwGetKey (g_window, GLFW_KEY_PAGE_UP)) {
			cam_pos[1] += cam_speed * elapsed_seconds;
			cam_moved = true;
		}
		if (glfwGetKey (g_window, GLFW_KEY_PAGE_DOWN)) {
			cam_pos[1] -= cam_speed * elapsed_seconds;
			cam_moved = true;
		}
		if (glfwGetKey (g_window, GLFW_KEY_W)) {
			cam_pos[2] -= cam_speed * elapsed_seconds;
			cam_moved = true;
		}
		if (glfwGetKey (g_window, GLFW_KEY_S)) {
			cam_pos[2] += cam_speed * elapsed_seconds;
			cam_moved = true;
		}
		if (glfwGetKey (g_window, GLFW_KEY_LEFT)) {
			cam_yaw += cam_yaw_speed * elapsed_seconds;
			cam_moved = true;
		}
		if (glfwGetKey (g_window, GLFW_KEY_RIGHT)) {
			cam_yaw -= cam_yaw_speed * elapsed_seconds;
			cam_moved = true;
		}
		// update view matrix
		if (cam_moved) {
			mat4 T = translate (identity_mat4 (), vec3 (-cam_pos[0],
                -cam_pos[1], -cam_pos[2])); // cam translation
			mat4 R = rotate_y_deg (identity_mat4 (), -cam_yaw); // 
			mat4 view_mat = R * T;
			glUniformMatrix4fv (view_mat_location, 1, GL_FALSE, view_mat.m);
		}
		
		
		if (GLFW_PRESS == glfwGetKey (g_window, GLFW_KEY_ESCAPE)) {
			glfwSetWindowShouldClose (g_window, 1);
		}
		// put the stuff we've been drawing onto the display
		glfwSwapBuffers (g_window);
	}
	
	// close GL context and any other GLFW resources
	glfwTerminate();
	return 0;
}
Esempio n. 5
0
void load_curv(GLuint program, GLuint first_loc)
{
	Parameters::getInstance()->g_uniform_locations[first_loc] =
		glGetUniformLocation (program, "u_scene_size");
		
	Parameters::getInstance()->g_uniform_locations[first_loc+1] =
		glGetUniformLocation (program, "densities");
	Parameters::getInstance()->g_uniform_locations[first_loc+2] =
		glGetUniformLocation (program, "u_viewport");

	Parameters::getInstance()->g_uniform_locations[first_loc+3] =
		glGetUniformLocation (program, "solid_wireframe");
		
	Parameters::getInstance()->g_uniform_locations[first_loc+4] =
		glGetUniformLocation (program, "u_curv_radius");
    Parameters::getInstance()->g_uniform_locations[first_loc+5] =
        glGetUniformLocation (program, "u_kmin");
    Parameters::getInstance()->g_uniform_locations[first_loc+6] =
        glGetUniformLocation (program, "u_kmax");

    Parameters::getInstance()->g_uniform_locations[first_loc+7] =
        glGetUniformLocation (program, "u_size_tex");
	
	Parameters::getInstance()->g_uniform_locations[first_loc+8] = 
		glGetUniformLocation(program, "u_curv_dir");
	Parameters::getInstance()->g_uniform_locations[first_loc+9] = 
		glGetUniformLocation(program, "u_curv_val");
		
	Parameters::getInstance()->g_uniform_locations[first_loc+10] = 
		glGetUniformLocation(program, "u_lvl");
	Parameters::getInstance()->g_uniform_locations[first_loc+11] = 
		glGetUniformLocation(program, "u_triangle_normals");
		
	Parameters::getInstance()->g_uniform_locations[first_loc+12] = 
		glGetUniformLocation(program, "u_time");
		
	Parameters::getInstance()->g_uniform_locations[first_loc+13] = 
		glGetUniformLocation(program, "u_spheresubdiv");
	
	/*Parameters::getInstance()->g_uniform_locations[first_loc+7] =
        glGetUniformLocation (program, "u_ground_truth");*/

	/*Parameters::getInstance()->g_uniform_locations[first_loc+15] = 
		glGetUniformLocation(program, "u_fromtexture");*/

	/*
	Parameters::getInstance()->g_uniform_locations[first_loc+12] = 
		glGetUniformLocation(program, "u_xyz2_tex");

	Parameters::getInstance()->g_uniform_locations[first_loc+13] = 
		glGetUniformLocation(program, "u_xy_yz_xz_tex");
		
	Parameters::getInstance()->g_uniform_locations[first_loc+14] = 
		glGetUniformLocation(program, "u_xyz_tex");
	*/
	
	/*
	Parameters::getInstance()->g_uniform_locations[first_loc+3] =
		glGetUniformLocation (program, "u_tan_fovy");
	Parameters::getInstance()->g_uniform_locations[first_loc+4] =
		glGetUniformLocation (program, "u_scale");
	*/
	/*Parameters::getInstance()->g_uniform_locations[first_loc+6] =
		glGetUniformLocation (program, "u_camera_pos");*/
}
Esempio n. 6
0
	int main()
	{
		glfwInit();
		glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
		glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
		glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
		glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

		GLFWwindow* window = glfwCreateWindow(800, 600, "Learning some OpenGL", nullptr, nullptr);
		glfwMakeContextCurrent(window);

		glfwSetKeyCallback(window, key_callback);

		//Check to make sure the window is not null. If it is, terminate.
		if (window == nullptr)
		{
			std::cout << "Failed to create GLFW window" << std::endl;
			glfwTerminate();
			return -1;
		}

		//Initialise GLEW
		//glewExperimental allows us to use modern techniques. Not setting it to true might lead to complications
		glewExperimental = GL_TRUE;
		if (glewInit() != GLEW_OK)
		{
			std::cout << "Failed to initialise GLEW" << std::endl;
			return -1;
		}

		//Tell OpenGL the size of the window, or in this case the viewport, that we wish to render to
		glViewport(0, 0, 800, 600);

		Shader shader("shaders/texture_shader.vs", "shaders/texture_shader.frag");
		//Tutorial Three
		texture_triangle();

		//Simple loop
		while (!glfwWindowShouldClose(window))
		{
			glfwPollEvents();

			//Set clear colour to ensure that we're actually rendering something
			glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
			glClear(GL_COLOR_BUFFER_BIT);

			//Bind the texture
			glBindTexture(GL_TEXTURE_2D, texture);
			glBindTexture(GL_TEXTURE_2D, texture_two);

			glActiveTexture(GL_TEXTURE0);
			glBindTexture(GL_TEXTURE_2D, texture);
			glUniform1i(glGetUniformLocation(shader.Program, "texture_one"), 0);
			glActiveTexture(GL_TEXTURE1);
			glBindTexture(GL_TEXTURE_2D, texture_two);
			glUniform1i(glGetUniformLocation(shader.Program, "texture_two"), 1);
			//Get location
			GLuint location = glGetUniformLocation(shader.Program, "mix_variable");
			glUniform1f(location, mix_variable);

			//Drawning
			shader.use();
			glBindVertexArray(VAO);
			glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
			glBindVertexArray(0);

			glfwSwapBuffers(window);
		}

		//Cleanup
		glDeleteVertexArrays(1, &VAO);
		glDeleteBuffers(1, &VBO);

		glfwTerminate();
		return 0;
	}
Esempio n. 7
0
int main(void)
{
    GLFWwindow* window;

    window = init("Billboards", 640, 480);
    if(!window)
    {
        return -1;
    }

    glEnable(GL_DEPTH_TEST);

    Camera camera(CAMERA_PERSPECTIVE, 45.0f, 0.1f, 1000.0f, 640.0f, 480.0f);
    camera.setPosition(0.0f, 0.0f, -3.0f);
    setCamera(&camera); // The camera updating is handled in ../common/util.cpp

    glm::mat4 model;

    GLuint program;
    {
        GLuint vertex = createShader(VERTEX_SRC, GL_VERTEX_SHADER);
        GLuint fragment = createShader(FRAGMENT_SRC, GL_FRAGMENT_SHADER);
        program = createShaderProgram(vertex, fragment);
        linkShader(program);
        validateShader(program);
        glDetachShader(program, vertex);
        glDeleteShader(vertex);
        glDetachShader(program, fragment);
        glDeleteShader(fragment);
    }
    GLuint billboardProgram;
    {
        GLuint vertex = createShader(VERTEX_BB_SRC, GL_VERTEX_SHADER);
        GLuint fragment = createShader(FRAGMENT_BB_SRC, GL_FRAGMENT_SHADER);
        billboardProgram = createShaderProgram(vertex, fragment);
        linkShader(billboardProgram);
        validateShader(billboardProgram);
        glDetachShader(program, vertex);
        glDeleteShader(vertex);
        glDetachShader(program, fragment);
        glDeleteShader(fragment);
    }

    glUseProgram(program);

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

    GLuint vbo;
    glGenBuffers(1, &vbo);

    float vertices[] =
    {
        // x   y      z     r     g     b     u     v
        -0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f,
         0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
         0.5f,  0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
         0.5f,  0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
        -0.5f,  0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f,
        -0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f,
    
        -0.5f, -0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f,
         0.5f, -0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
         0.5f,  0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
         0.5f,  0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
        -0.5f,  0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f,
        -0.5f, -0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f,
    
        -0.5f,  0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
        -0.5f,  0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
        -0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f,
        -0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f,
        -0.5f, -0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f,
        -0.5f,  0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
    
         0.5f,  0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
         0.5f,  0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
         0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f,
         0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f,
         0.5f, -0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f,
         0.5f,  0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
    
        -0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f,
         0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
         0.5f, -0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
         0.5f, -0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
        -0.5f, -0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f,
        -0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f,
    
        -0.5f,  0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f,
         0.5f,  0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
         0.5f,  0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
         0.5f,  0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
        -0.5f,  0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f,
        -0.5f,  0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f
    };

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

    glEnableVertexAttribArray(0); // position
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), 0);
    glEnableVertexAttribArray(1); // color
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (void*)(3 * sizeof(GLfloat)));
    glEnableVertexAttribArray(2); // texture coordinates
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (void*)(6 * sizeof(GLfloat)));

    float verts_bb[] =
    {
        -0.5f, -0.5f,
        0.5f,  -0.5f,
        -0.5f, 0.5f,
        0.5f, 0.5f
    };
    GLuint vbo_bb;
    glGenBuffers(1, &vbo_bb);
    GLuint vao_bb;
    glGenVertexArrays(1, &vao_bb);
    glBindVertexArray(vao_bb);
    glBindBuffer(GL_ARRAY_BUFFER, vbo_bb);
    glBufferData(GL_ARRAY_BUFFER, sizeof(verts_bb), verts_bb, GL_STATIC_DRAW);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0);

    glUseProgram(billboardProgram);
    glUniform3f(glGetUniformLocation(billboardProgram, "center"), 0.0f, 2.0f, 0.0f);
    glUniform2f(glGetUniformLocation(billboardProgram, "size"), 0.5f, 0.5f);

    int w, h;
    GLuint texture = loadImage("image.png", &w, &h, 0, false);
    glUniform1i(glGetUniformLocation(billboardProgram, "tex"), 0);
    glUseProgram(program);
    glUniform1i(glGetUniformLocation(program, "tex"), 0);
    
    glClearColor(0.75f, 0.75f, 0.75f, 1.0f);

    glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);

    while(!glfwWindowShouldClose(window))
    {
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        updateCamera(640, 480, window);

        // Draw the cube
        glUseProgram(program);
        glBindVertexArray(vao);

        GLint modelUL = glGetUniformLocation(program, "model");
        glUniformMatrix4fv(modelUL, 1, GL_FALSE, glm::value_ptr(model));
        GLint viewUL = glGetUniformLocation(program, "view");
        glUniformMatrix4fv(viewUL, 1, GL_FALSE, glm::value_ptr(camera.getView()));
        GLint projUL = glGetUniformLocation(program, "projection");
        glUniformMatrix4fv(projUL, 1, GL_FALSE, glm::value_ptr(camera.getProjection()));

        glDrawArrays(GL_TRIANGLES, 0, 36);

        // Draw the billboard
        glBindVertexArray(vao_bb);
        glUseProgram(billboardProgram);

        viewUL = glGetUniformLocation(billboardProgram, "view");
        glUniformMatrix4fv(viewUL, 1, GL_FALSE, glm::value_ptr(camera.getView()));
        projUL = glGetUniformLocation(billboardProgram, "proj");
        glUniformMatrix4fv(projUL, 1, GL_FALSE, glm::value_ptr(camera.getProjection()));
        glUniform1i(glGetUniformLocation(billboardProgram, "fixedSize"), 0);
        glUniform3f(glGetUniformLocation(billboardProgram, "camRight"), camera.getRightVector().x, camera.getRightVector().y, camera.getRightVector().z);
        glUniform3f(glGetUniformLocation(billboardProgram, "camUp"), camera.getUpVector().x, camera.getUpVector().y, camera.getUpVector().z);

        glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    // Clean up
    glDeleteBuffers(1, &vbo);
    glDeleteVertexArrays(1, &vao);
    glDeleteBuffers(1, &vbo_bb);
    glDeleteVertexArrays(1, &vao_bb);
    glDeleteProgram(program);
    glDeleteProgram(billboardProgram);
    glDeleteTextures(1, &texture);

    glfwTerminate();
    return 0;
}
static void
Init(void)
{
   static const char *fragShaderText =
      "uniform float StipplePattern[16]; \n"
      "varying vec2 stippleCoord; \n"
      "void main() \n"
      "{ \n"
      "   // check the stipple pattern and discard if value is zero \n"
      "   // TODO: we should really undo the perspective interpolation here \n"
      "   // so that it's linear. \n"
      "   float stip = StipplePattern[int(fract(stippleCoord.x) * 16.0)]; \n"
      "   if (stip == 0.0) \n"
      "      discard; \n"
      "   gl_FragColor = gl_Color; \n"
      "} \n";
   static const char *vertShaderText =
      "void main() \n"
      "{ \n"
      "   gl_FrontColor = gl_Color; \n"
      "   gl_Position = ftransform(); \n"
      "} \n";
   static const char *geomShaderText =
      "#version 150 \n"
      "#extension GL_ARB_geometry_shader4: enable \n"
      "uniform vec2 ViewportSize; \n"
      "uniform float StippleFactor; \n"
      "out vec2 stippleCoord; \n"
      "void main() \n"
      "{ \n"
      "   vec4 pos0 = gl_PositionIn[0]; \n"
      "   vec4 pos1 = gl_PositionIn[1]; \n"
      "   // Convert eye coords to window coords \n"
      "   // Note: we're off by a factor of two here, make up for that below \n"
      "   vec2 p0 = pos0.xy / pos0.w * ViewportSize; \n"
      "   vec2 p1 = pos1.xy / pos1.w * ViewportSize; \n"
      "   float len = length(p0.xy - p1.xy); \n"
      "   // Emit first vertex \n"
      "   gl_FrontColor = gl_FrontColorIn[0]; \n"
      "   gl_Position = pos0; \n"
      "   stippleCoord.x = 0.0; \n"
      "   EmitVertex(); \n"
      "   // Emit second vertex \n"
      "   gl_FrontColor = gl_FrontColorIn[1]; \n"
      "   gl_Position = pos1; \n"
      "   stippleCoord.x = len / StippleFactor / 32.0; // Note: not 16, see above \n"
      "   EmitVertex(); \n"
      "} \n";

   if (!ShadersSupported())
      exit(1);

   if (!glutExtensionSupported("GL_ARB_geometry_shader4")) {
      fprintf(stderr, "Sorry, GL_ARB_geometry_shader4 is not supported.\n");
      exit(1);
   }

   VertShader = CompileShaderText(GL_VERTEX_SHADER, vertShaderText);
   FragShader = CompileShaderText(GL_FRAGMENT_SHADER, fragShaderText);
   GeomShader = CompileShaderText(GL_GEOMETRY_SHADER_ARB, geomShaderText);
   assert(GeomShader);

   Program = LinkShaders3(VertShader, GeomShader, FragShader);
   assert(Program);
   CheckError(__LINE__);

   /*
    * The geometry shader accepts lines and produces lines.
    */
   glProgramParameteriARB(Program, GL_GEOMETRY_INPUT_TYPE_ARB,
                          GL_LINES);
   glProgramParameteriARB(Program, GL_GEOMETRY_OUTPUT_TYPE_ARB,
                          GL_LINE_STRIP);
   glProgramParameteriARB(Program, GL_GEOMETRY_VERTICES_OUT_ARB, 4);
   CheckError(__LINE__);

   glLinkProgramARB(Program);

   /* check link */
   {
      GLint stat;
      GetProgramiv(Program, GL_LINK_STATUS, &stat);
      if (!stat) {
         GLchar log[1000];
         GLsizei len;
         GetProgramInfoLog(Program, 1000, &len, log);
         fprintf(stderr, "Shader link error:\n%s\n", log);
      }
   }

   glUseProgram(Program);

   uViewportSize = glGetUniformLocation(Program, "ViewportSize");
   uStippleFactor = glGetUniformLocation(Program, "StippleFactor");
   uStipplePattern = glGetUniformLocation(Program, "StipplePattern");

   glUniform1f(uStippleFactor, StippleFactor);

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

   printf("GL_RENDERER = %s\n",(const char *) glGetString(GL_RENDERER));

   assert(glIsProgram(Program));
   assert(glIsShader(FragShader));
   assert(glIsShader(VertShader));
   assert(glIsShader(GeomShader));


   glLineStipple(StippleFactor, StipplePattern);
   SetStippleUniform(StippleFactor, StipplePattern);

   MakePoints();
}
Esempio n. 9
0
bool ParticleSystem::initGL(void)
{
  INFO("Initializing OpenGL subsystem");

  /* compile shaders */
  //if (!m_shader.build(m_vert_shader, m_frag_shader))
  if (!m_shader_particle_colors.buildFiles(utils::fs::AssetsPath(m_vert_shader_particle_colors_file),
                                           utils::fs::AssetsPath(m_frag_shader_particle_colors_file)))
  {
    ERROR("Failed to compile shaders for particle colors program");
    return false;
  }

  if (!m_shader_uniform_color.buildFiles(utils::fs::AssetsPath(m_vert_shader_uniform_color_file),
                                         utils::fs::AssetsPath(m_frag_shader_uniform_color_file)))
  {
    ERROR("Failed to compile shaders for uniform color program");
    return false;
  }

  if (!m_shader_bounding_volume.buildFiles(utils::fs::AssetsPath(m_vert_shader_bounding_volume_file),
                                           utils::fs::AssetsPath(m_frag_shader_bounding_volume_file)))
  {
    ERROR("Failed to compile shaders for bounding volume program");
    return false;
  }

  /* per particle colors program */
  GLuint pc_prog = m_shader_particle_colors.getID();
  
  glUseProgram(pc_prog);
  //glUniform3f(glGetUniformLocation(prog, "light_pos"), 0.0f, 0.0f, -1.0f);     // shader assumes the position is normalized
  //glUniform3f(glGetUniformLocation(prog, "light_pos"), -1.0f, 1.0f, -1.0f);
  glUniform3f(glGetUniformLocation(pc_prog, "light_pos"), -10.0f, 10.0f, 15.0f);
  glUniform3f(glGetUniformLocation(pc_prog, "light_col_a"), 0.8f, 0.8f, 0.8f);
  glUniform3f(glGetUniformLocation(pc_prog, "light_col_d"), 1.0f, 1.0f, 1.0f);
  glUniform3f(glGetUniformLocation(pc_prog, "light_col_s"), 1.0f, 1.0f, 1.0f);

  /* uniform color program */
  GLuint uc_prog = m_shader_uniform_color.getID();
  
  glUseProgram(uc_prog);
  glUniform3f(glGetUniformLocation(uc_prog, "light_pos"), -10.0f, 10.0f, 15.0f);
  glUniform3f(glGetUniformLocation(uc_prog, "light_col_a"), 0.8f, 0.8f, 0.8f);
  glUniform3f(glGetUniformLocation(uc_prog, "light_col_d"), 1.0f, 1.0f, 1.0f);
  glUniform3f(glGetUniformLocation(uc_prog, "light_col_s"), 1.0f, 1.0f, 1.0f);
  glUniform3f(glGetUniformLocation(uc_prog, "particle_col"), 0.5f, 0.5f, 1.0f);

  /* bounding volume program */
  GLuint bv_prog = m_shader_bounding_volume.getID();

  glUseProgram(bv_prog);

  glUniform3f(glGetUniformLocation(bv_prog, "dimensions"),
              (m_volume_max.s[0] - m_volume_min.s[0]) * 0.5f,
              (m_volume_max.s[1] - m_volume_min.s[1]) * 0.5f,
              (m_volume_max.s[2] - m_volume_min.s[2]) * 0.5f);
  glUniform3f(glGetUniformLocation(bv_prog, "col"), 1.0f, 1.0f, 1.0f);

  glUseProgram(0);

  /* load models */
  if (!geom::genSphere(m_particle_geom))
  //if (!geom::genPrism(m_particle_geom))
  {
    ERROR("Failed to generate sphere model");
    return false;
  }

  return true;
}
void FaceCullingComponent::Draw(float DeltaSeconds)
{
	mShaderContainer.UseProgram();
	glBindVertexArray(mVAO);
	glActiveTexture(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_2D, mTextureDiffuse);
	glActiveTexture(GL_TEXTURE1);
	glBindTexture(GL_TEXTURE_2D, mTextureSpecular);

	//Set up uniforms
	// MODEL, VIEW, PROJECTION
	GLint modelLocation = glGetUniformLocation(mShaderContainer.Program(), "model");
	if (modelLocation == -1)
	{
		cout << "Model location = -1" << endl;
		return;
	}

	GLint viewLocation = glGetUniformLocation(mShaderContainer.Program(), "view");
	if (viewLocation == -1)
	{
		cout << "View location = -1" << endl;
		return;
	}

	GLint projectionLocation = glGetUniformLocation(mShaderContainer.Program(), "projection");
	if (projectionLocation == -1)
	{
		cout << "Projection location = -1" << endl;
		return;
	}

	glUniformMatrix4fv(viewLocation, 1, GL_FALSE, glm::value_ptr(mCamera->GetViewMatrix()));
	glUniformMatrix4fv(projectionLocation, 1, GL_FALSE, glm::value_ptr(mCamera->GetProjectionMatrix()));

	//TODO: look for steel propoerties for the steel borders (shininess)
	// MATERIAL PROPERTIES
	GLint matDiffuseLocation = glGetUniformLocation(mShaderContainer.Program(), "material.diffuse");
	GLint matSpecularLocation = glGetUniformLocation(mShaderContainer.Program(), "material.specular");
	GLint matShineLocation = glGetUniformLocation(mShaderContainer.Program(), "material.shininess");
	glUniform1i(matDiffuseLocation, 0);
	glUniform1i(matSpecularLocation, 1);
	glUniform1f(matShineLocation, 8.0f);

	//DIRECTIONAL LIGHT
	GLint lightDirectionLocation;
	GLint lightAmbientLocation;
	GLint lightDiffuseLocation;
	GLint lightSpecularLocation;
	lightDirectionLocation = glGetUniformLocation(mShaderContainer.Program(), "directionalLight.direction");
	lightAmbientLocation = glGetUniformLocation(mShaderContainer.Program(), "directionalLight.ambient");
	lightDiffuseLocation = glGetUniformLocation(mShaderContainer.Program(), "directionalLight.diffuse");
	lightSpecularLocation = glGetUniformLocation(mShaderContainer.Program(), "directionalLight.specular");
	glUniform3f(lightDirectionLocation, -0.2f, -1.0f, -0.3f);
	glUniform3f(lightAmbientLocation, 0.2f, 0.2f, 0.2f);
	glUniform3f(lightDiffuseLocation, 1.0f, 1.0f, 1.0f); // Let’s darken the light a bit to fit the scene
	glUniform3f(lightSpecularLocation, 1.0f, 1.0f, 1.0f);

	// POINT LIGHT
	GLint lightPositionLocation;
	for (int i = 0; i < mPointLightPositions.size(); ++i)
	{
		lightPositionLocation = glGetUniformLocation(mShaderContainer.Program(), ("pointLights[" + std::to_string(i) + "].position").c_str());
		lightAmbientLocation = glGetUniformLocation(mShaderContainer.Program(), ("pointLights[" + std::to_string(i) + "].ambient").c_str());
		lightDiffuseLocation = glGetUniformLocation(mShaderContainer.Program(), ("pointLights[" + std::to_string(i) + "].diffuse").c_str());
		lightSpecularLocation = glGetUniformLocation(mShaderContainer.Program(), ("pointLights[" + std::to_string(i) + "].specular").c_str());
		GLint lightIntensityLocation = glGetUniformLocation(mShaderContainer.Program(), ("pointLights[" + std::to_string(i) + "].intensity").c_str());
		GLint lightKcLocation = glGetUniformLocation(mShaderContainer.Program(), ("pointLights[" + std::to_string(i) + "].Kc").c_str());
		GLint lightKlLocation = glGetUniformLocation(mShaderContainer.Program(), ("pointLights[" + std::to_string(i) + "].Kl").c_str());
		GLint lightKqLocation = glGetUniformLocation(mShaderContainer.Program(), ("pointLights[" + std::to_string(i) + "].Kq").c_str());
		glUniform3f(lightPositionLocation, mPointLightPositions[i].x, mPointLightPositions[i].y, mPointLightPositions[i].z);
		glUniform3f(lightAmbientLocation, 0.2f, 0.2f, 0.2f);
		glUniform3f(lightDiffuseLocation, 1.0f, 1.0f, 1.0f);
		glUniform3f(lightSpecularLocation, 1.0f, 1.0f, 1.0f);
		glUniform1f(lightIntensityLocation, 0.5f);
		glUniform1f(lightKcLocation, 1.0f);
		glUniform1f(lightKlLocation, 0.09f);
		glUniform1f(lightKqLocation, 0.032f);
	}

	
	//Camera position and direction
	GLint cameraPositionLocation = glGetUniformLocation(mShaderContainer.Program(), "cameraPosition");
	glm::vec3 camPos = mCamera->GetPosition();
	glm::vec3 camDirection = mCamera->GetDirection();
	glUniform3f(cameraPositionLocation, camPos.x, camPos.y, camPos.z);

	// SPOT LIGHT
	lightPositionLocation = glGetUniformLocation(mShaderContainer.Program(), "spotLight.position");
	lightDirectionLocation = glGetUniformLocation(mShaderContainer.Program(), "spotLight.direction");
	GLint lightInnerAngleLocation = glGetUniformLocation(mShaderContainer.Program(), "spotLight.innerAngle");
	GLint lightOuterAngleLocation = glGetUniformLocation(mShaderContainer.Program(), "spotLight.outerAngle");
	lightAmbientLocation = glGetUniformLocation(mShaderContainer.Program(), "spotLight.ambient");
	lightDiffuseLocation = glGetUniformLocation(mShaderContainer.Program(), "spotLight.diffuse");
	lightSpecularLocation = glGetUniformLocation(mShaderContainer.Program(), "spotLight.specular");
	glUniform3f(lightPositionLocation, camPos.x, camPos.y, camPos.z); //We use the camera's position, simulating a flashlight (follows the player)
	glUniform3f(lightDirectionLocation, camDirection.x, camDirection.y, camDirection.z);
	glUniform1f(lightInnerAngleLocation, glm::radians(5.0f));
	glUniform1f(lightOuterAngleLocation, glm::radians(20.0f)); //TODO: implement attenuation, the spot light shines infinitely.
	glUniform3f(lightAmbientLocation, 0.2f, 0.2f, 0.2f);
	glUniform3f(lightDiffuseLocation, 1.0f, 1.0f, 1.0f);
	glUniform3f(lightSpecularLocation, 1.0f, 1.0f, 1.0f);


	for (size_t i = 0; i < mCubePositions.size(); ++i)
	{
		glm::mat4 model;
		model = glm::translate(glm::mat4(), mCubePositions[i]);
		float angle = 20.0f * i;
		model = glm::rotate(model, glm::radians(angle), glm::vec3(0.2f, 0.5f, 0.5f));

		glUniformMatrix4fv(modelLocation, 1, GL_FALSE, glm::value_ptr(model));
		glDrawArrays(GL_TRIANGLES, 0, 36);
	}

	mShaderLight.UseProgram();
	//Set up uniforms
	modelLocation = glGetUniformLocation(mShaderLight.Program(), "model");
	if (modelLocation == -1)
	{
		cout << "Model location = -1" << endl;
		return;
	}

	viewLocation = glGetUniformLocation(mShaderLight.Program(), "view");
	if (viewLocation == -1)
	{
		cout << "View location = -1" << endl;
		return;
	}

	projectionLocation = glGetUniformLocation(mShaderLight.Program(), "projection");
	if (projectionLocation == -1)
	{
		cout << "Projection location = -1" << endl;
		return;
	}

	glUniformMatrix4fv(viewLocation, 1, GL_FALSE, glm::value_ptr(mCamera->GetViewMatrix()));
	glUniformMatrix4fv(projectionLocation, 1, GL_FALSE, glm::value_ptr(mCamera->GetProjectionMatrix()));

	for (int i = 0; i < mPointLightPositions.size(); ++i)
	{
		glUniformMatrix4fv(modelLocation, 1, GL_FALSE, glm::value_ptr(glm::translate(glm::mat4(), mPointLightPositions[i])));
		glDrawArrays(GL_TRIANGLES, 0, 36);
	}

	glUseProgram(0);
	glBindVertexArray(0);
}
Esempio n. 11
0
	bool CGUIManager::CreateDeviceObjects()
	{
		Window->MakeContextCurrent();

		// Backup GL state
		GLint last_texture, last_array_buffer, last_vertex_array;
		glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
		glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer);
		glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array);

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

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

		ShaderHandle = glCreateProgram();
		VertHandle = glCreateShader(GL_VERTEX_SHADER);
		FragHandle = glCreateShader(GL_FRAGMENT_SHADER);
		glShaderSource(VertHandle, 1, &vertex_shader, 0);
		glShaderSource(FragHandle, 1, &fragment_shader, 0);
		glCompileShader(VertHandle);
		glCompileShader(FragHandle);
		glAttachShader(ShaderHandle, VertHandle);
		glAttachShader(ShaderHandle, FragHandle);
		glLinkProgram(ShaderHandle);

		AttribLocationTex = glGetUniformLocation(ShaderHandle, "Texture");
		AttribLocationProjMtx = glGetUniformLocation(ShaderHandle, "ProjMtx");
		AttribLocationPosition = glGetAttribLocation(ShaderHandle, "Position");
		AttribLocationUV = glGetAttribLocation(ShaderHandle, "UV");
		AttribLocationColor = glGetAttribLocation(ShaderHandle, "Color");

		glGenBuffers(1, &VboHandle);
		glGenBuffers(1, &ElementsHandle);

		glGenVertexArrays(1, &VaoHandle);
		glBindVertexArray(VaoHandle);
		glBindBuffer(GL_ARRAY_BUFFER, VboHandle);
		glEnableVertexAttribArray(AttribLocationPosition);
		glEnableVertexAttribArray(AttribLocationUV);
		glEnableVertexAttribArray(AttribLocationColor);

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

		CreateFontsTexture();

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

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

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

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

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

	shader->program = glCreateProgram();

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

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

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

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

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

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

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

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

			GPU_shader_free(shader);
			return NULL;
		}
	}

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

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

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

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

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

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

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

			GPU_shader_free(shader);
			return NULL;
		}
	}

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

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

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

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

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

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

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

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

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

		GPU_shader_free(shader);
		return NULL;
	}

#ifdef WITH_OPENSUBDIV
	/* TODO(sergey): Find a better place for this. */
	if (use_opensubdiv && GLEW_VERSION_4_1) {
		glProgramUniform1i(shader->program,
		                   glGetUniformLocation(shader->program, "FVarDataBuffer"),
		                   31);  /* GL_TEXTURE31 */
	}
#endif

	return shader;
}
Esempio n. 14
0
/////////////////////////////////
// Initialize function
/////////////////////////////////
void init() {

  /*select clearing (background) color*/
  glClearColor(0.0, 0.0, 0.0, 1.0);

   rotateYEarth = 1;
   rotateZEarth = 1;


    //populate our arrays
    //spherevertcount = generateSphere(2, 30);

    vec4 sphereverts[2592];
	vec2 spheretexcoords[2592]; // 2592
	vec3 spherenormals[2592];
	vec4 spheretangents[2592];

	vec4 cloudverts[2592];
	vec2 cloudtexcoords[2592]; // 2592
	vec3 cloudnormals[2592];
	vec4 cloudtangents[2592];

	CreateSphere(sphereverts, spheretexcoords, spherenormals, spheretangents, 2, 0,0,0);

	// create cloud
	CreateSphere(cloudverts, cloudtexcoords, cloudnormals, cloudtangents, 2, 0,0,0);

	/////////////////////////////////////////
	// Create a vertex array object
	spherevao = new GLuint[1];
	spherevbo = new GLuint[3];

	cloudvao = new GLuint[1];
	cloudvbo = new GLuint[3];

	//////////////////////////
	// earth buffer
	//////////////////////////
	glGenVertexArrays( 1, &spherevao[0] );

	// Create and initialize any buffer objects
	glBindVertexArray( spherevao[0] );
	glGenBuffers( 2, &spherevbo[0] );
	glBindBuffer( GL_ARRAY_BUFFER, spherevbo[0] );
	glBufferData( GL_ARRAY_BUFFER, VertexCount*sizeof(vec4), sphereverts, GL_STATIC_DRAW);

	glBindBuffer( GL_ARRAY_BUFFER, spherevbo[1] );
	glBufferData( GL_ARRAY_BUFFER, VertexCount*sizeof(vec2), spheretexcoords, GL_STATIC_DRAW);

	glBindBuffer( GL_ARRAY_BUFFER, spherevbo[2] );
	glBufferData( GL_ARRAY_BUFFER, VertexCount*sizeof(vec3), spherenormals, GL_STATIC_DRAW);

	//////////////////////
	// Cloud buffer
	//////////////////////
	glGenVertexArrays( 1, &cloudvao[0] );

	// Create and initialize any buffer objects
	glBindVertexArray( cloudvao[0] );
	glGenBuffers( 2, &cloudvbo[0] );
	glBindBuffer( GL_ARRAY_BUFFER, cloudvbo[0] );
	glBufferData( GL_ARRAY_BUFFER, VertexCount*sizeof(vec4), cloudverts, GL_STATIC_DRAW);

	glBindBuffer( GL_ARRAY_BUFFER, cloudvbo[1] );
	glBufferData( GL_ARRAY_BUFFER, VertexCount*sizeof(vec2), cloudtexcoords, GL_STATIC_DRAW);

	glBindBuffer( GL_ARRAY_BUFFER, cloudvbo[2] );
	glBufferData( GL_ARRAY_BUFFER, VertexCount*sizeof(vec3), cloudnormals, GL_STATIC_DRAW);

   // Load shaders and use the resulting shader program
    
	programAllFeatures = InitShader( "vshader-phongshading.glsl", "fshader-phongshading.glsl" );
	programColor = InitShader( "vshader-color.glsl", "fshader-color.glsl" );
	programCloud = InitShader( "vshader-cloud.glsl", "fshader-cloud.glsl" );


    glUseProgram(programAllFeatures);

	// Create a vertex array object
 //   glGenVertexArrays( 1, &vao[0] );

 //   // Create and initialize any buffer objects
	//glBindVertexArray( vao[0] );
	//glGenBuffers( 2, &vbo[0] );
 //   glBindBuffer( GL_ARRAY_BUFFER, vbo[0] );
 //   glBufferData( GL_ARRAY_BUFFER, spherevertcount*sizeof(vec4), sphere_verts, GL_STATIC_DRAW);
	//

	////and now our colors for each vertex
	//glBindBuffer( GL_ARRAY_BUFFER, vbo[1] );
	//glBufferData( GL_ARRAY_BUFFER, spherevertcount*sizeof(vec3), sphere_normals, GL_STATIC_DRAW );

	// setupShader(programAllFeatures);


	model_view = glGetUniformLocation(programAllFeatures, "model_view");
	projection = glGetUniformLocation(programAllFeatures, "projection");
	
	setupEarthShader(programAllFeatures, spherevao, spherevbo);

	
	// set up cloud shader
	// This is where I have error that whenever I use setupearthshader for cloud
	// I have bad images rendered. 
	// I don't understand and keep looking errors why but give up cloud
	// setupEarthShader(programCloud, cloudvao, cloudvbo);

	glUseProgram(programAllFeatures);


    ILuint ilTexID[5]; /* ILuint is a 32bit unsigned integer.

    //Variable texid will be used to store image name. */
   

	ilInit(); /* Initialization of OpenIL */
	ilGenImages(5, ilTexID); /* Generation of three image names for OpenIL image loading */
	glGenTextures(5, texName); //and we eventually want the data in an OpenGL texture
 

	/////////////////////////////////////////
	// EARTH BUFFERS
	////////////////////////////////////////////////////
	
	// load color map
	if ( true )
	{
		ilBindImage(ilTexID[0]); /* Binding of IL image name */
		loadTexFile("images/Earth.png");
		glBindTexture(GL_TEXTURE_2D, texName[0]); //bind OpenGL texture name

		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR); //GL_NEAREST);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); //GL_NEAREST);
	   //Note how we depend on OpenIL to supply information about the file we just loaded in
		glTexImage2D(GL_TEXTURE_2D, 0, ilGetInteger(IL_IMAGE_BPP), ilGetInteger(IL_IMAGE_WIDTH), ilGetInteger(IL_IMAGE_HEIGHT),0,
		ilGetInteger(IL_IMAGE_FORMAT), ilGetInteger(IL_IMAGE_TYPE), ilGetData());

		glGenerateMipmap(GL_TEXTURE_2D);
	}

	// load cloud
	
	if (true)
	{
		glUseProgram(programCloud);

		ilBindImage(ilTexID[1]); /* Binding of IL image name */
		glBindTexture(GL_TEXTURE_2D, texName[1]); //bind OpenGL texture name
		loadTexFile("images/earthcloudmap.png");
		

		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR); //GL_NEAREST);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); //GL_NEAREST);
	   //Note how we depend on OpenIL to supply information about the file we just loaded in
		glTexImage2D(GL_TEXTURE_2D, 0, ilGetInteger(IL_IMAGE_BPP), ilGetInteger(IL_IMAGE_WIDTH), ilGetInteger(IL_IMAGE_HEIGHT),0,
		ilGetInteger(IL_IMAGE_FORMAT), ilGetInteger(IL_IMAGE_TYPE), ilGetData());
		glGenerateMipmap(GL_TEXTURE_2D);		
	}


	// Spec map
	if (true)
	{
		glUseProgram(programAllFeatures);

		ilBindImage(ilTexID[2]); /* Binding of IL image name */
		glBindTexture(GL_TEXTURE_2D, texName[2]); //bind OpenGL texture name
		loadTexFile("images/EarthSpec.png");
		

		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR); //GL_NEAREST);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); //GL_NEAREST);
	   //Note how we depend on OpenIL to supply information about the file we just loaded in
		glTexImage2D(GL_TEXTURE_2D, 0, ilGetInteger(IL_IMAGE_BPP), ilGetInteger(IL_IMAGE_WIDTH), ilGetInteger(IL_IMAGE_HEIGHT),0,
		ilGetInteger(IL_IMAGE_FORMAT), ilGetInteger(IL_IMAGE_TYPE), ilGetData());
		glGenerateMipmap(GL_TEXTURE_2D);
	}


	// Normal map
	if (true)
	{
		ilBindImage(ilTexID[3]); /* Binding of IL image name */
		glBindTexture(GL_TEXTURE_2D, texName[3]); //bind OpenGL texture name
		loadTexFile("images/EarthNormal.png");
		

		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR); //GL_NEAREST);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); //GL_NEAREST);
	   //Note how we depend on OpenIL to supply information about the file we just loaded in
		glTexImage2D(GL_TEXTURE_2D, 0, ilGetInteger(IL_IMAGE_BPP), ilGetInteger(IL_IMAGE_WIDTH), ilGetInteger(IL_IMAGE_HEIGHT),0,
		ilGetInteger(IL_IMAGE_FORMAT), ilGetInteger(IL_IMAGE_TYPE), ilGetData());
		glGenerateMipmap(GL_TEXTURE_2D);
	}

	// Night map
	if (true)
	{
		ilBindImage(ilTexID[4]); /* Binding of IL image name */
		glBindTexture(GL_TEXTURE_2D, texName[4]); //bind OpenGL texture name
		loadTexFile("images/EarthNight.png");
		

		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR); //GL_NEAREST);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); //GL_NEAREST);
	   //Note how we depend on OpenIL to supply information about the file we just loaded in
		glTexImage2D(GL_TEXTURE_2D, 0, ilGetInteger(IL_IMAGE_BPP), ilGetInteger(IL_IMAGE_WIDTH), ilGetInteger(IL_IMAGE_HEIGHT),0,
		ilGetInteger(IL_IMAGE_FORMAT), ilGetInteger(IL_IMAGE_TYPE), ilGetData());
		glGenerateMipmap(GL_TEXTURE_2D);
	}


	////////////////////////////////////////////////
    ilDeleteImages(5, ilTexID); //we're done with OpenIL, so free up the memory

	////////////////////////////////////////////////////

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

    texMap = glGetUniformLocation(programAllFeatures, "texture");
	glUniform1i(texMap, 0);//assign this one to texture unit 0
	
	cloudMap = glGetUniformLocation(programCloud, "cloudtexture");
	glUniform1i(cloudMap, 1);//assign cloud map to  texture unit 1

	specMap = glGetUniformLocation(programAllFeatures, "spectexture");
	glUniform1i(specMap, 2);//assign spec map to 2 texture unit
	
	normalMap = glGetUniformLocation(programAllFeatures, "normalMap");
	glUniform1i(normalMap, 3);//assign normal map to 3 texture unit
	
	nightMap = glGetUniformLocation(programAllFeatures, "nighttexture");
	glUniform1i(nightMap, 4);//assign spec map to 4 texture unit
	
	
	// setup lightning
	vAmbientDiffuseColor = glGetAttribLocation(programAllFeatures, "vAmbientDiffuseColor");
	vSpecularColor = glGetAttribLocation(programAllFeatures, "vSpecularColor");
	vSpecularExponent = glGetAttribLocation(programAllFeatures, "vSpecularExponent");
	light_position = glGetUniformLocation(programAllFeatures, "light_position");
	light_color = glGetUniformLocation(programAllFeatures, "light_color");
	ambient_light = glGetUniformLocation(programAllFeatures, "ambient_light");
	
  //Only draw the things in the front layer
	glEnable(GL_DEPTH_TEST);
}
Esempio n. 15
0
/////////////////////////////////////////
// Display
/////////////////////////////////////////
void display(void)
{
  /*clear all pixels*/
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    
    mv = LookAt(vec4(0, 0, 10+z_distance, 1.0), vec4(0, 0, 0, 1.0), vec4(0, 1, 0, 0.0)) * RotateX(-90) * RotateZ(rotateZEarth);

	//mv = mv *  RotateY(view_roty) ;//RotateZ(view_rotz); //RotateX(view_rotx)
	

	//////////////////////////////
	// Display all features
	/////////////////////////////

	if ( true )
	{
	glUseProgram(programAllFeatures);
	
	model_view = glGetUniformLocation(programAllFeatures, "model_view");
	projection = glGetUniformLocation(programAllFeatures, "projection");

	stack.push(mv);
	mv = mv*Scale(2,2,2);
	glUniformMatrix4fv(model_view, 1, GL_TRUE, mv);
	
	
	glVertexAttrib4fv(vAmbientDiffuseColor, vec4(.7, 0.7, 0.7, 1));
	glVertexAttrib4fv(vSpecularColor, vec4(1.0f,1.0f,1.0f,1.0f));
	glVertexAttrib1f(vSpecularExponent, 50.0);
	glUniform4fv(light_position, 1, vec4(50.0, 0.0, 0.0, 1));
	glUniform4fv(light_color, 1, vec4(1,1,1,1));
	glUniform4fv(ambient_light, 1, vec4(.5, .5, .5, 5));

	
	// texture unit 0 : color earth
	glActiveTexture(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_2D, texName[0]); //which texture do we want?
	glDrawArrays( GL_QUAD_STRIP, 0, VertexCount );
	mv = stack.pop();

	// texture unit 1 : cloud earth

	//stack.push(mv);
	//mv = mv*Scale(2.05,2.05,2.05);
	//glUniformMatrix4fv(model_view, 1, GL_TRUE, mv);
	//glActiveTexture(GL_TEXTURE1);
	//glBindTexture(GL_TEXTURE_2D, texName[1]); //which texture do we want?
	//glDrawArrays( GL_QUAD_STRIP, 0, VertexCount );
	//mv = stack.pop();


	stack.push(mv);
	// texture unit 2 : specular earth
	glActiveTexture(GL_TEXTURE2);
	glBindTexture(GL_TEXTURE_2D, texName[2]); //which texture do we want?
	glDrawArrays( GL_QUAD_STRIP, 0, VertexCount );


	// texture unit 4 : night earth
	glActiveTexture(GL_TEXTURE4);
	glBindTexture(GL_TEXTURE_2D, texName[4]); //which texture do we want?
	glDrawArrays( GL_QUAD_STRIP, 0, VertexCount );
	mv = stack.pop();

	}

	//////////////////////////////
	// Display cloud
	/////////////////////////////

	if ( false )
	{
	glUseProgram(programAllFeatures);
	model_view = glGetUniformLocation(programAllFeatures, "model_view");
	projection = glGetUniformLocation(programAllFeatures, "projection");
	
	//glUseProgram(programCloud);
	//model_view = glGetUniformLocation(programCloud, "model_view");
	//projection = glGetUniformLocation(programCloud, "projection");

	
	
	glActiveTexture(GL_TEXTURE1);
	mv = mv*Scale(2.01,2.01,2.01);
	glUniformMatrix4fv(model_view, 1, GL_TRUE, mv);

	glBindTexture(GL_TEXTURE_2D, texName[1]); //which texture do we want?
	glDrawArrays( GL_QUAD_STRIP, 0, VertexCount );

	}

	
    glUseProgram(programAllFeatures);

    glFlush();
    /*start processing buffered OpenGL routines*/
    glutSwapBuffers();
}
void EmitterShader::LoadShader(const char* vsh, const char* fsh)
{
  program = build_program_from_assets(vsh, fsh);
  // Attributes
  this->a_pID = glGetAttribLocation(this->program, "a_pID");
  this->a_pRadiusOffset = glGetAttribLocation(this->program, "a_pRadiusOffset");
  this->a_pVelocityOffset = glGetAttribLocation(this->program, "a_pVelocityOffset");
  this->a_pDecayOffset = glGetAttribLocation(this->program, "a_pDecayOffset");
  this->a_pSizeOffset = glGetAttribLocation(this->program, "a_pSizeOffset");
  this->a_pColorOffset = glGetAttribLocation(this->program, "a_pColorOffset");

  // Uniforms
  this->u_ProjectionMatrix = glGetUniformLocation(this->program, "u_ProjectionMatrix");
  this->u_Gravity = glGetUniformLocation(this->program, "u_Gravity");
  this->u_Time = glGetUniformLocation(this->program, "u_Time");
  this->u_eRadius = glGetUniformLocation(this->program, "u_eRadius");
  this->u_eVelocity = glGetUniformLocation(this->program, "u_eVelocity");
  this->u_eDecay = glGetUniformLocation(this->program, "u_eDecay");
  this->u_eSizeStart = glGetUniformLocation(this->program, "u_eSizeStart");
  this->u_eSizeEnd = glGetUniformLocation(this->program, "u_eSizeEnd");
  this->u_eColorStart = glGetUniformLocation(this->program, "u_eColorStart");
  this->u_eColorEnd = glGetUniformLocation(this->program, "u_eColorEnd");
  this->u_Texture = glGetUniformLocation(this->program, "u_Texture");
  this->u_ePosition = glGetUniformLocation(this->program, "u_ePosition");
}
Esempio n. 17
0
    SceneManager::SceneManager(GLint width, GLint height)
#endif
    {
        Log << Function << endl;

        // The projection matrix is represented by the perspective matrix given by glm, assign it to each one of the objects
        GLfloat aspect = static_cast<GLfloat>(width) / static_cast<GLfloat>(height);
        projectionMatrix = glm::perspective(
            45.0f,      // Field of view, is the amount of zoom. A wide angle is 90 and a narrow angle is 30
            aspect,     // Depends on the size of the window
            0.1f,       // Near clipping plane
            500.0f      // Far clipping plane
        );

        // Read the resources.txt file to obtain the valid configuration for the engine
        string resourcesFileName = "resources.txt";
#if defined(__ANDROID__)
        AAssetManager* mgr = AAssetManager_fromJava(*env, assetManager);
        AAsset* pFile = AAssetManager_open(mgr, resourcesFileName.c_str(), AASSET_MODE_UNKNOWN);
        if (!pFile)
#else
        ifstream resourcesFile(resourcesFileName, ios::in);
        if (!resourcesFile.is_open())
#endif
        {
            Log << Error << "Unable to read the resources file: " << resourcesFileName << endl;
            terminate();
        }

#if defined(__ANDROID__)
        // Get the file size
        size_t fileSize = AAsset_getLength(pFile);
        // Read data from the file
        char* pData = (char*)calloc(fileSize + 1, sizeof(char));
        AAsset_read(pFile, pData, fileSize);
        // fix the string to be zero-terminated
        pData[fileSize] = 0;
        // Copy the data to a stringstream
        stringstream resourcesFile(pData);
        AAsset_close(pFile);
        free(pData);
#endif

        Log << Debug << "Parsing the resources.txt file." << endl;
        string line, name, vertex, fragment, object, texture, projection, modelview;
        vector<string> cubeTextures{ NumCubeFaces };
        GLuint size, bufferType;
        vec3 pos, scl, rot;
        char token;
        bool finished = true;

        while (getline(resourcesFile, line))
        {
            stringstream ssLine(line);
            // Ignore empty lines on the configuration file
            if(line.size() == 0)
                continue;

            ssLine >> token;
            switch (token)
            {
            // If the line is a comment get the next token
            case '#':
                continue;
            // Start of object definition
            case '.':
                // Create a new scene object
                Log << Debug << "Starting an object definition." << endl;
                sceneobjects.push_back(make_unique<SceneObject>());
                finished = false;
                break;
            // End of an object definition
            case '-':
                Log << Debug << "End an object definition." << endl;
                finished = true;
                break;
            // Attributes used on the shaders
            case 'A':
                ssLine >> name >> size >> bufferType;
                Log << Debug << "Adding the attribute: " << name << endl;
                attributes.push_back(make_unique<Variable>(name, size, (BufferType)bufferType));
                break;
            // Uniforms used on the shaders
            case 'U':
                ssLine >> name;
                Log << Debug << "Adding the uniform: " << name << endl;
                uniforms.push_back(make_unique<Variable>(name));
                break;
            // Shaders creation
            case 'S':
                ssLine >> vertex >> fragment;
                Log << Debug << "Creating the shaders." << endl;
#if defined (__ANDROID__)
                sceneobjects.back()->SetShader(make_shared<Shader>(&mgr, vertex, fragment, attributes, uniforms));
#else
                sceneobjects.back()->SetShader(make_shared<Shader>(vertex, fragment, attributes, uniforms));
#endif
                break;
            // Object definitions
            case 'O':
                ssLine >> object;
                Log << Debug << "Loading a model." << endl;
#if defined (__ANDROID__)
                sceneobjects.back()->SetMesh(make_unique<Mesh>(&mgr, object, sceneobjects.back()->GetShader()));
#else
                sceneobjects.back()->SetMesh(make_unique<Mesh>(object, sceneobjects.back()->GetShader()));
#endif
                break;
            // Textures
            case 'T':
                ssLine >> texture;
                Log << Debug << "Loading a texture." << endl;
#if defined(__ANDROID__)
                sceneobjects.back()->SetTexture(make_unique<Texture>(&mgr, texture, sceneobjects.back()->GetShader()));
#else
                sceneobjects.back()->SetTexture(make_unique<Texture>(texture, sceneobjects.back()->GetShader()));
#endif
                break;
            // Initial coordinates
            case 'C':
                Log << Debug << "Adding coordinates to the object." << endl;
                ssLine >> pos.x >> pos.y >> pos.z >> scl.x >> scl.y >> scl.z >> rot.x >> rot.y >> rot.z >> angle;
                sceneobjects.back()->SetCoordinates(pos, scl, rot, angle);
                break;
            // Projection matrix
            case 'P':
                ssLine >> projection;
                break;
            // Modelview matrix
            case 'M':
                ssLine >> modelview;
                break;
            // Skybox
            case 'B':
                Log << Debug << "Adding a skybox." << endl;
                ssLine >> cubeTextures[0] >> cubeTextures[1] >> cubeTextures[2] >> cubeTextures[3] >> cubeTextures[4] >> cubeTextures[5];
                sceneobjects.back()->SetSkymap();
#if defined(__ANDROID__)
                sceneobjects.back()->SetMesh(make_unique<Mesh>(&mgr, string(""), sceneobjects.back()->GetShader()));
                sceneobjects.back()->SetTexture(make_unique<Texture>(&mgr, cubeTextures, sceneobjects.back()->GetShader()));
#else
                sceneobjects.back()->SetMesh(make_unique<Mesh>(string(""), sceneobjects.back()->GetShader()));
                sceneobjects.back()->SetTexture(make_unique<Texture>(cubeTextures, sceneobjects.back()->GetShader()));
#endif
                break;
            // Terrain Heightmap
            case 'H':
                Log << Debug << "Loading the terrain." << endl;
                ssLine >> texture >> object;
#if defined(__ANDROID__)
                sceneobjects.back()->SetTexture(make_unique<Texture>(&mgr, texture, sceneobjects.back()->GetShader()));
                sceneobjects.back()->SetMesh(make_unique<Mesh>(&mgr, object, sceneobjects.back()->GetShader(), &sceneobjects.back()->GetTexture()));
#else
                sceneobjects.back()->SetTexture(make_unique<Texture>(texture, sceneobjects.back()->GetShader()));
                sceneobjects.back()->SetMesh(make_unique<Mesh>(object, sceneobjects.back()->GetShader(), &sceneobjects.back()->GetTexture()));
#endif
                break;
            default:
                continue;
            }

            // Check if the definition of an object is complete or if more lines are needed
            if (finished)
            {
                // Get the projection and modelview uniforms
                if (!projection.empty())
                {
                    sceneobjects.back()->SetProjectionUni(glGetUniformLocation(sceneobjects.back()->GetShader()->getProgramObject(), "Projection"));
                    projection.clear();
                }
                if (!modelview.empty())
                {
                    sceneobjects.back()->SetModelviewUni(glGetUniformLocation(sceneobjects.back()->GetShader()->getProgramObject(), "Modelview"));
                    modelview.clear();
                }

                // Clear the attributes and uniforms in order to load the next object
                attributes.clear();
                uniforms.clear();
            }
        }
#if !defined(__ANDROID__)
        // Close de the resources file
        resourcesFile.close();
#endif

        // Set the initial position of the camera
        camera = vec3(2.5f, -1.0f, -5.0f);

        // Initial value of the rotation angle
        angle = 0.0f;
    }
Esempio n. 18
0
LinkedShader::LinkedShader(Shader *vs, Shader *fs, u32 vertType, bool useHWTransform, LinkedShader *previous)
		: useHWTransform_(useHWTransform), program(0), dirtyUniforms(0) {
	program = glCreateProgram();

	glAttachShader(program, vs->shader);
	glAttachShader(program, fs->shader);

	// Bind attribute locations to fixed locations so that they're
	// the same in all shaders. We use this later to minimize the calls to
	// glEnableVertexAttribArray and glDisableVertexAttribArray.
	glBindAttribLocation(program, ATTR_POSITION, "position");
	glBindAttribLocation(program, ATTR_TEXCOORD, "texcoord");
	glBindAttribLocation(program, ATTR_NORMAL, "normal");
	glBindAttribLocation(program, ATTR_W1, "w1");
	glBindAttribLocation(program, ATTR_W2, "w2");
	glBindAttribLocation(program, ATTR_COLOR0, "color0");
	glBindAttribLocation(program, ATTR_COLOR1, "color1");

#ifndef USING_GLES2
	if (gl_extensions.ARB_blend_func_extended) {
		// Dual source alpha
		glBindFragDataLocationIndexed(program, 0, 0, "fragColor0");
		glBindFragDataLocationIndexed(program, 0, 1, "fragColor1");
	} else if (gl_extensions.VersionGEThan(3, 3, 0)) {
		glBindFragDataLocation(program, 0, "fragColor0");
	}
#endif

	glLinkProgram(program);

	// Detaching shaders is annoying when debugging with gDebugger
	// so let's not do that on Windows.
#ifdef USING_GLES
	glDetachShader(program, vs->shader);
	glDetachShader(program, fs->shader);
#endif

	GLint linkStatus = GL_FALSE;
	glGetProgramiv(program, GL_LINK_STATUS, &linkStatus);
	if (linkStatus != GL_TRUE) {
		GLint bufLength = 0;
		glGetProgramiv(program, GL_INFO_LOG_LENGTH, &bufLength);
		if (bufLength) {
			char* buf = new char[bufLength];
			glGetProgramInfoLog(program, bufLength, NULL, buf);
#ifdef ANDROID
			ELOG("Could not link program:\n %s", buf);
#endif
			ERROR_LOG(G3D, "Could not link program:\n %s", buf);
			ERROR_LOG(G3D, "VS:\n%s", vs->source().c_str());
			ERROR_LOG(G3D, "FS:\n%s", fs->source().c_str());
			Reporting::ReportMessage("Error in shader program link: info: %s / fs: %s / vs: %s", buf, fs->source().c_str(), vs->source().c_str());
#ifdef SHADERLOG
			OutputDebugStringUTF8(buf);
			OutputDebugStringUTF8(vs->source().c_str());
			OutputDebugStringUTF8(fs->source().c_str());
#endif
			delete [] buf;	// we're dead!
		}
		// Prevent a buffer overflow.
		numBones = 0;
		return;
	}

	INFO_LOG(G3D, "Linked shader: vs %i fs %i", (int)vs->shader, (int)fs->shader);

	u_tex = glGetUniformLocation(program, "tex");
	u_proj = glGetUniformLocation(program, "u_proj");
	u_proj_through = glGetUniformLocation(program, "u_proj_through");
	u_texenv = glGetUniformLocation(program, "u_texenv");
	u_fogcolor = glGetUniformLocation(program, "u_fogcolor");
	u_fogcoef = glGetUniformLocation(program, "u_fogcoef");
	u_alphacolorref = glGetUniformLocation(program, "u_alphacolorref");
	u_colormask = glGetUniformLocation(program, "u_colormask");
	u_stencilReplaceValue = glGetUniformLocation(program, "u_stencilReplaceValue");

	// Transform
	u_view = glGetUniformLocation(program, "u_view");
	u_world = glGetUniformLocation(program, "u_world");
	u_texmtx = glGetUniformLocation(program, "u_texmtx");
	if (vertTypeGetWeightMask(vertType) != GE_VTYPE_WEIGHT_NONE)
		numBones = TranslateNumBones(vertTypeGetNumBoneWeights(vertType));
	else
		numBones = 0;

#ifdef USE_BONE_ARRAY
	u_bone = glGetUniformLocation(program, "u_bone");
#else
	for (int i = 0; i < 8; i++) {
		char name[10];
		sprintf(name, "u_bone%i", i);
		u_bone[i] = glGetUniformLocation(program, name);
	}
#endif

	// Lighting, texturing
	u_ambient = glGetUniformLocation(program, "u_ambient");
	u_matambientalpha = glGetUniformLocation(program, "u_matambientalpha");
	u_matdiffuse = glGetUniformLocation(program, "u_matdiffuse");
	u_matspecular = glGetUniformLocation(program, "u_matspecular");
	u_matemissive = glGetUniformLocation(program, "u_matemissive");
	u_uvscaleoffset = glGetUniformLocation(program, "u_uvscaleoffset");

	for (int i = 0; i < 4; i++) {
		char temp[64];
		sprintf(temp, "u_lightpos%i", i);
		u_lightpos[i] = glGetUniformLocation(program, temp);
		sprintf(temp, "u_lightdir%i", i);
		u_lightdir[i] = glGetUniformLocation(program, temp);
		sprintf(temp, "u_lightatt%i", i);
		u_lightatt[i] = glGetUniformLocation(program, temp);
		sprintf(temp, "u_lightangle%i", i);
		u_lightangle[i] = glGetUniformLocation(program, temp);
		sprintf(temp, "u_lightspotCoef%i", i);
		u_lightspotCoef[i] = glGetUniformLocation(program, temp);
		sprintf(temp, "u_lightambient%i", i);
		u_lightambient[i] = glGetUniformLocation(program, temp);
		sprintf(temp, "u_lightdiffuse%i", i);
		u_lightdiffuse[i] = glGetUniformLocation(program, temp);
		sprintf(temp, "u_lightspecular%i", i);
		u_lightspecular[i] = glGetUniformLocation(program, temp);
	}

	attrMask = 0;
	if (-1 != glGetAttribLocation(program, "position")) attrMask |= 1 << ATTR_POSITION;
	if (-1 != glGetAttribLocation(program, "texcoord")) attrMask |= 1 << ATTR_TEXCOORD;
	if (-1 != glGetAttribLocation(program, "normal")) attrMask |= 1 << ATTR_NORMAL;
	if (-1 != glGetAttribLocation(program, "w1")) attrMask |= 1 << ATTR_W1;
	if (-1 != glGetAttribLocation(program, "w2")) attrMask |= 1 << ATTR_W2;
	if (-1 != glGetAttribLocation(program, "color0")) attrMask |= 1 << ATTR_COLOR0;
	if (-1 != glGetAttribLocation(program, "color1")) attrMask |= 1 << ATTR_COLOR1;

	availableUniforms = 0;
	if (u_proj != -1) availableUniforms |= DIRTY_PROJMATRIX;
	if (u_proj_through != -1) availableUniforms |= DIRTY_PROJTHROUGHMATRIX;
	if (u_texenv != -1) availableUniforms |= DIRTY_TEXENV;
	if (u_alphacolorref != -1) availableUniforms |= DIRTY_ALPHACOLORREF;
	if (u_colormask != -1) availableUniforms |= DIRTY_COLORMASK;
	if (u_fogcolor != -1) availableUniforms |= DIRTY_FOGCOLOR;
	if (u_fogcoef != -1) availableUniforms |= DIRTY_FOGCOEF;
	if (u_texenv != -1) availableUniforms |= DIRTY_TEXENV;
	if (u_uvscaleoffset != -1) availableUniforms |= DIRTY_UVSCALEOFFSET;
	if (u_world != -1) availableUniforms |= DIRTY_WORLDMATRIX;
	if (u_view != -1) availableUniforms |= DIRTY_VIEWMATRIX;
	if (u_texmtx != -1) availableUniforms |= DIRTY_TEXMATRIX;
	if (u_stencilReplaceValue != -1) availableUniforms |= DIRTY_STENCILREPLACEVALUE;

	// Looping up to numBones lets us avoid checking u_bone[i]
	for (int i = 0; i < numBones; i++) {
		if (u_bone[i] != -1)
			availableUniforms |= DIRTY_BONEMATRIX0 << i;
	}
	if (u_ambient != -1) availableUniforms |= DIRTY_AMBIENT;
	if (u_matambientalpha != -1) availableUniforms |= DIRTY_MATAMBIENTALPHA;
	if (u_matdiffuse != -1) availableUniforms |= DIRTY_MATDIFFUSE;
	if (u_matemissive != -1) availableUniforms |= DIRTY_MATEMISSIVE;
	if (u_matspecular != -1) availableUniforms |= DIRTY_MATSPECULAR;
	for (int i = 0; i < 4; i++) {
		if (u_lightdir[i] != -1 ||
				u_lightspecular[i] != -1 ||
				u_lightpos[i] != -1)
			availableUniforms |= DIRTY_LIGHT0 << i;
	}

	glUseProgram(program);

	// Default uniform values
	glUniform1i(u_tex, 0);
	// The rest, use the "dirty" mechanism.
	dirtyUniforms = DIRTY_ALL;
	use(vertType, previous);
}
Esempio n. 19
0
void init () {

   printf("init()\n");

   glClearColor(.3f, .3f, .3f, 1.f);

   g_context.vert_id = load_shader(
    GL_VERTEX_SHADER,
    "attribute vec4 a_position;              \n"
    "attribute vec4 a_color;                 \n"
    "uniform float u_time;                   \n"
    "varying vec4 v_color;                   \n"
    "void main()                             \n"
    "{                                       \n"
    "    float sz = sin(u_time);             \n"
    "    float cz = cos(u_time);             \n"
    "    mat4 rot = mat4(                    \n"
    "     cz, -sz, 0,  0,                    \n"
    "     sz,  cz, 0,  0,                    \n"
    "     0,   0,  1,  0,                    \n"
    "     0,   0,  0,  1                     \n"
    "    );                                  \n"
    "    gl_Position = a_position * rot;     \n"
    "    v_color = a_color;                  \n"
    "}                                       \n"
   );
   printf("- vertex shader loaded\n");

   g_context.frag_id = load_shader(
    GL_FRAGMENT_SHADER,
    "precision mediump float;                \n"
    "varying vec4 v_color;                   \n"
    "void main()                             \n"
    "{                                       \n"
    "    gl_FragColor = v_color;             \n"
    "}                                       \n"
   );
   printf("- fragment shader loaded\n");

   g_context.prog_id = glCreateProgram();
   assert(g_context.prog_id);
   glAttachShader(g_context.prog_id, g_context.vert_id);
   glAttachShader(g_context.prog_id, g_context.frag_id);
   glBindAttribLocation(g_context.prog_id, Context::Position_loc, "a_position");
   glBindAttribLocation(g_context.prog_id, Context::Color_loc, "a_color");
   glLinkProgram(g_context.prog_id);
   GLint linked = 0;
   glGetProgramiv(g_context.prog_id, GL_LINK_STATUS, &linked);
   assert(linked);
   g_context.u_time_loc = glGetUniformLocation(g_context.prog_id, "u_time");
   assert(g_context.u_time_loc >= 0);
   glUseProgram(g_context.prog_id);
   printf("- shader program linked & bound\n");

   struct Vertex { float x, y, z; unsigned char r, g, b, a; };

   const Vertex vtcs[3] = {
    {  0.f,  .5f, 0.f,   255, 0, 0, 255 },
    { -.5f, -.5f, 0.f,   0, 255, 0, 255 },
    {  .5f, -.5f, 0.f,   0, 0, 255, 255 }
   };

   glGenBuffers(1, &g_context.geom_id);
   assert(g_context.geom_id);
   glBindBuffer(GL_ARRAY_BUFFER, g_context.geom_id);
   glBufferData(GL_ARRAY_BUFFER, sizeof(vtcs), vtcs, GL_STATIC_DRAW);
   glVertexAttribPointer(Context::Position_loc, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), offset(0));
   glEnableVertexAttribArray(Context::Position_loc);
   glVertexAttribPointer(Context::Color_loc, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(Vertex), offset(3 * sizeof(float)));
   glEnableVertexAttribArray(Context::Color_loc);
   printf("- geometry created & bound\n");
}
Esempio n. 20
0
int main(int argc, char** argv) {
	// Standard stuff...
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
	glutInitWindowSize(1080, 600);
	glutCreateWindow("Lighted Cube");
	glutReshapeFunc(changeViewport);
	glutKeyboardFunc(keyboardFunc);
	glutDisplayFunc(render);
	glewInit();

	initMatrices(); // New <========================================


	// Make a shader
	char* vertexShaderSourceCode = readFile("vertexShader.vsh");
	char* fragmentShaderSourceCode = readFile("fragmentShader.fsh");
	GLuint vertShaderID = makeVertexShader(vertexShaderSourceCode);
	GLuint fragShaderID = makeFragmentShader(fragmentShaderSourceCode);
	shaderProgramID = makeShaderProgram(vertShaderID, fragShaderID);

	// Create the "remember all"
	glGenVertexArrays(1, &vao);
	glBindVertexArray(vao);

	glGenBuffers(1, &vbo);
	glBindBuffer(GL_ARRAY_BUFFER, vbo);
	// Create the buffer, but don't load anything yet
	//glBufferData(GL_ARRAY_BUFFER, 7*NUM_VERTICES*sizeof(GLfloat), NULL, GL_STATIC_DRAW);
	glBufferData(GL_ARRAY_BUFFER, 6 * NUM_VERTICES*sizeof(GLfloat), NULL, GL_STATIC_DRAW); // NEW! - we're only loading vertices and normals (6 elements, not 7)

	// Load the vertex points
	glBufferSubData(GL_ARRAY_BUFFER, 0, 3 * NUM_VERTICES*sizeof(GLfloat), vertices);
	// Load the colors right after that
	//glBufferSubData(GL_ARRAY_BUFFER, 3*NUM_VERTICES*sizeof(GLfloat),4*NUM_VERTICES*sizeof(GLfloat), colors);
	glBufferSubData(GL_ARRAY_BUFFER, 3 * NUM_VERTICES*sizeof(GLfloat), 3 * NUM_VERTICES*sizeof(GLfloat), normals);


#ifdef USING_INDEX_BUFFER
	glGenBuffers(1, &indexBufferID);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBufferID);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, NUM_INDICES*sizeof(GLuint), indices, GL_STATIC_DRAW);
#endif

	// Find the position of the variables in the shader
	positionID = glGetAttribLocation(shaderProgramID, "s_vPosition");
	normalID = glGetAttribLocation(shaderProgramID, "s_vNormal"); // NEW
	lightID1 = glGetUniformLocation(shaderProgramID, "vLight1");    // NEW
	lightID2 = glGetUniformLocation(shaderProgramID, "vLight2");    // NEW

	// ============ New! glUniformLocation is how you pull IDs for uniform variables===============
	perspectiveMatrixID = glGetUniformLocation(shaderProgramID, "mP");
	viewMatrixID = glGetUniformLocation(shaderProgramID, "mV");
	modelMatrixID = glGetUniformLocation(shaderProgramID, "mM");
	allRotsMatrixID = glGetUniformLocation(shaderProgramID, "mRotations"); // NEW
	//=============================================================================================

	glVertexAttribPointer(positionID, 3, GL_FLOAT, GL_FALSE, 0, 0);
	glVertexAttribPointer(normalID, 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(sizeof(vertices)));

	glUseProgram(shaderProgramID);
	glEnableVertexAttribArray(positionID);
	glEnableVertexAttribArray(normalID);    // NEW

	glEnable(GL_CULL_FACE);  // NEW! - we're doing real 3D now
	glCullFace(GL_BACK);     // Other options? GL_FRONT and GL_FRONT_AND_BACK
	glEnable(GL_DEPTH_TEST); // Make sure the depth buffer is on.  As you draw a pixel, update the screen only if it's closer than previous ones

	glutMainLoop();

	return 0;
}
Esempio n. 21
0
tvint tv_material_get_uniform(tv_material *material, tvchar *name)
{
	/* TODO: obviously this is a horrible hack.
	 * this function shouldn't exist anyway */
	return glGetUniformLocation(material->passes[0]->program, name);
}
Esempio n. 22
0
/**
 * Function for initialization.
 */
GLUSboolean init(GLUSvoid)
{
	// Matrix for the model
	GLfloat	model[16];

	GLUSshape cube;

	GLUStgaimage image;

	GLUStextfile vertexSource;

	GLUStextfile fragmentSource;

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

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

	// Build and ...
	glusBuildProgram(&g_program, (const GLUSchar**)&vertexSource.text, 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);

	glusCreateCubef(&cube, 0.5f);
	numberIndices = cube.numberIndices;

	// 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_textureLocation = glGetUniformLocation(g_program.program, "firstTexture");

	// 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/glGetAttribLocation.xml
	g_texCoordLocation = glGetAttribLocation(g_program.program, "texCoord");

	// ToDo:
	glBindFragDataLocation(g_program.program, 0, "fragColor");

	// 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, cube.numberVertices*4*sizeof(GLfloat), (GLfloat*)cube.vertices, 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, cube.numberVertices*3*sizeof(GLfloat), (GLfloat*)cube.normals, GL_STATIC_DRAW);

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

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

	// http://www.opengl.org/sdk/docs/man/xhtml/glBufferData.xml
	glBufferData(GL_ARRAY_BUFFER, cube.numberVertices*2*sizeof(GLfloat), (GLfloat*)cube.texCoords, 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, cube.numberIndices*sizeof(GLuint), (GLuint*)cube.indices, GL_STATIC_DRAW);

	glusDestroyShapef(&cube);

	glusLoadTgaImage("crate.tga", &image);

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

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

	// http://www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/teximage2d.html
	glTexImage2D(GL_TEXTURE_2D, 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_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

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

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

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

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

	// Calculate the model matrix ...
	glusLoadIdentityf(model);
	glusRotateRzRyRxf(model, 30.0f, 30.0f, 0.0f);
	// ... and the view matrix ...
	glusLookAtf(g_modelView, 0.0f, 0.0f, 5.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f);
	// ... to get the final model view matrix
	glusMultMatrixf(g_modelView, g_modelView, model);

	// http://www.opengl.org/sdk/docs/man/xhtml/glUniform.xml
	glUniformMatrix4fv(g_modelViewLocation, 1, GL_FALSE, g_modelView);

	// 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/glBindBuffer.xml
	glBindBuffer(GL_ARRAY_BUFFER, g_texCoords);

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

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

	// http://www.opengl.org/sdk/docs/man/xhtml/glUniform.xml
	glUniform1i(g_textureLocation, 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;
}
Esempio n. 23
0
void draw_windmill(windmill_t* w, float dt)
{
    glUseProgram(programs[WINDMILL_PROGRAM]);

	// Send in additional params
	glUniformMatrix4fv(glGetUniformLocation(programs[WINDMILL_PROGRAM], "projectionMatrix"), 1, GL_TRUE, projectionMatrix);
	glUniformMatrix4fv(glGetUniformLocation(programs[WINDMILL_PROGRAM], "camMatrix"), 1, GL_TRUE, camMatrix);

    glUniformMatrix4fv(glGetUniformLocation(programs[WINDMILL_PROGRAM], "lightSourcesColors"), 1, GL_FALSE, lightSourcesColors);
    glUniformMatrix4fv(glGetUniformLocation(programs[WINDMILL_PROGRAM], "lightSourcesDirections"), 1, GL_FALSE, lightSourcesDirections);

    float camera_position[3]; camera_position[0] = position.x;  camera_position[1] = position.y;  camera_position[2] = position.z;
	glUniform3fv(glGetUniformLocation(programs[WINDMILL_PROGRAM], "camera_position"), 1, camera_position);

    w->bladeangle += dt*windspeed/3;

	Rz(w->bladeangle, w->bladerotationMatrix);
    GLfloat bladeBaseMatrix[16];
    Mult(w->windmillMDLMatrix[WINDMILL_BASE], w->bladecenterMatrix, work[0]);
    Mult(work[0], w->bladerotationMatrix, bladeBaseMatrix);

    {
        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, billboards[WOOD_TEXTURE]);
        glActiveTexture(GL_TEXTURE1);
        glBindTexture(GL_TEXTURE_2D, billboards[WOOD_TEXTURE]);

        glUniform1i(glGetUniformLocation(programs[WINDMILL_PROGRAM], "firstTexUnit"), 0);
        glUniform1i(glGetUniformLocation(programs[WINDMILL_PROGRAM], "secondTexUnit"), 1);
        glUniformMatrix4fv(glGetUniformLocation(programs[WINDMILL_PROGRAM], "baseMatrix"), 1, GL_TRUE, bladeBaseMatrix);
        int i = 0;
        for(i = 0; i < 4; ++i) {
            glUniformMatrix4fv(glGetUniformLocation(programs[WINDMILL_PROGRAM], "mdlMatrix"), 1, GL_TRUE, w->bladeMDLMatrix[i]);
            DrawModel(w->blades[i]);
        }
    }

    {
        glUniformMatrix4fv(glGetUniformLocation(programs[WINDMILL_PROGRAM], "baseMatrix"), 1, GL_TRUE, w->windmillMDLMatrix[WINDMILL_BASE]);
        int i = 0;

        for(i = 1; i < 3; ++i) {
            glUniformMatrix4fv(glGetUniformLocation(programs[WINDMILL_PROGRAM], "mdlMatrix"), 1, GL_TRUE, w->windmillMDLMatrix[i]);
            DrawModel(w->windmill[i]);
        }

        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, billboards[BRICK_TEXTURE]);
        glActiveTexture(GL_TEXTURE1);
        glBindTexture(GL_TEXTURE_2D, billboards[BRICK_CRACK_TEXTURE]);

        glUniformMatrix4fv(glGetUniformLocation(programs[WINDMILL_PROGRAM], "mdlMatrix"), 1, GL_TRUE, w->windmillMDLMatrix[WALLS]);
        DrawModel(w->windmill[WALLS]);
    }

	//printError("display windmill");
}
Esempio n. 24
0
int main() {
    int width = 640;
    int height = 480;
    
    if(glfwInit() == GL_FALSE) {
        std::cerr << "failed to init GLFW" << std::endl;
        return 1;
    }

    // select opengl version
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
 
    // create a window
    GLFWwindow *window;
    if((window = glfwCreateWindow(width, height, "03texture", 0, 0)) == 0) {
        std::cerr << "failed to open window" << std::endl;
        glfwTerminate();
        return 1;
    }
    
    glfwMakeContextCurrent(window);

    if(glxwInit()) {
        std::cerr << "failed to init GL3W" << std::endl;
        glfwDestroyWindow(window);
        glfwTerminate();
        return 1;
    }
    
    // shader source code
    std::string vertex_source =
        "#version 330\n"
        "layout(location = 0) in vec4 vposition;\n"
        "layout(location = 1) in vec2 vtexcoord;\n"
        "out vec2 ftexcoord;\n"
        "void main() {\n"
        "   ftexcoord = vtexcoord;\n"
        "   gl_Position = vposition;\n"
        "}\n";
        
    std::string fragment_source =
        "#version 330\n"
        "uniform sampler2D tex;\n" // texture uniform
        "in vec2 ftexcoord;\n"
        "layout(location = 0) out vec4 FragColor;\n"
        "void main() {\n"
        "   FragColor = texture(tex, ftexcoord);\n"
        "}\n";
   
    // program and shader handles
    GLuint shader_program, vertex_shader, fragment_shader;
    
    // we need these to properly pass the strings
    const char *source;
    int length;

    // create and compiler vertex shader
    vertex_shader = glCreateShader(GL_VERTEX_SHADER);
    source = vertex_source.c_str();
    length = vertex_source.size();
    glShaderSource(vertex_shader, 1, &source, &length); 
    glCompileShader(vertex_shader);
    if(!check_shader_compile_status(vertex_shader)) {
        glfwDestroyWindow(window);
        glfwTerminate();
        return 1;
    }
 
    // create and compiler fragment shader
    fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
    source = fragment_source.c_str();
    length = fragment_source.size();
    glShaderSource(fragment_shader, 1, &source, &length);   
    glCompileShader(fragment_shader);
    if(!check_shader_compile_status(fragment_shader)) {
        glfwDestroyWindow(window);
        glfwTerminate();
        return 1;
    }
        
    // create program
    shader_program = glCreateProgram();
    
    // attach shaders
    glAttachShader(shader_program, vertex_shader);
    glAttachShader(shader_program, fragment_shader);
    
    // link the program and check for errors
    glLinkProgram(shader_program);
    check_program_link_status(shader_program);
    
    // get texture uniform location
    GLint texture_location = glGetUniformLocation(shader_program, "tex");
    
    // vao and vbo handle
    GLuint vao, vbo, ibo;
 
    // generate and bind the vao
    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);
    
    // generate and bind the vertex buffer object
    glGenBuffers(1, &vbo);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
            
    // data for a fullscreen quad (this time with texture coords)
    GLfloat vertexData[] = {
    //  X     Y     Z           U     V     
       1.0f, 1.0f, 0.0f,       1.0f, 1.0f, // vertex 0
      -1.0f, 1.0f, 0.0f,       0.0f, 1.0f, // vertex 1
       1.0f,-1.0f, 0.0f,       1.0f, 0.0f, // vertex 2
      -1.0f,-1.0f, 0.0f,       0.0f, 0.0f, // vertex 3
    }; // 4 vertices with 5 components (floats) each

    // fill with data
    glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*4*5, vertexData, GL_STATIC_DRAW);
                    
           
    // set up generic attrib pointers
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5*sizeof(GLfloat), (char*)0 + 0*sizeof(GLfloat));
 
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5*sizeof(GLfloat), (char*)0 + 3*sizeof(GLfloat));
    
    
    // generate and bind the index buffer object
    glGenBuffers(1, &ibo);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
            
    GLuint indexData[] = {
        0,1,2, // first triangle
        2,1,3, // second triangle
    };

    // fill with data
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint)*2*3, indexData, GL_STATIC_DRAW);
    
    // "unbind" vao
    glBindVertexArray(0);

    // texture handle
    GLuint texture;
    
    // generate texture
    glGenTextures(1, &texture);

    // bind the texture
    glBindTexture(GL_TEXTURE_2D, texture);

    // create some image data
    std::vector<GLubyte> image(4*width*height);
    for(int j = 0;j<height;++j) {
        for(int i = 0;i<width;++i) {
            size_t index = j*width + i;
            image[4*index + 0] = 0xFF*(j/10%2)*(i/10%2); // R
            image[4*index + 1] = 0xFF*(j/13%2)*(i/13%2); // G
            image[4*index + 2] = 0xFF*(j/17%2)*(i/17%2); // B
            image[4*index + 3] = 0xFF;                   // A
        }
    }
    
    // set texture parameters
    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);
    
    // set texture content
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, &image[0]);
    
    while(!glfwWindowShouldClose(window)) {
        glfwPollEvents();
        
        // clear first
        glClear(GL_COLOR_BUFFER_BIT);
        
        // use the shader program
        glUseProgram(shader_program);

        // bind texture to texture unit 0
        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, texture);
        
        // set texture uniform
        glUniform1i(texture_location, 0);
        
        // bind the vao
        glBindVertexArray(vao);
        
        // draw
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
       
        // check for errors
        GLenum error = glGetError();
        if(error != GL_NO_ERROR) {
            std::cerr << error << std::endl;
            break;
        }
        
        // finally swap buffers
        glfwSwapBuffers(window);     
    }
    
    // delete the created objects
    
    glDeleteTextures(1, &texture);
    
    glDeleteVertexArrays(1, &vao);
    glDeleteBuffers(1, &vbo);
    glDeleteBuffers(1, &ibo);
    
    glDetachShader(shader_program, vertex_shader);	
    glDetachShader(shader_program, fragment_shader);
    glDeleteShader(vertex_shader);
    glDeleteShader(fragment_shader);
    glDeleteProgram(shader_program);

    glfwDestroyWindow(window);
    glfwTerminate();
    return 0;
}
Esempio n. 25
0
void CurrentApp::DefferedDraw(float dt)
{
	IconShader* IS = IconShader::GetInstance();

	// G-Pass: render out the albedo, position and normal
	glEnable(GL_DEPTH_TEST);
	glDisable(GL_BLEND);

	m_gPassTarget->SetAsActiveRenderTarget();
	glClearColor(0, 0, 0, 0);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	m_program = IS->UseProgram("GBuffer");

	// bind camera transforms
	int loc = glGetUniformLocation(m_program, "ProjectionView");
	glUniformMatrix4fv(loc, 1, GL_FALSE, &(m_camera->GetProjectionView()[0][0]));

	loc = glGetUniformLocation(m_program, "View");
	glUniformMatrix4fv(loc, 1, GL_FALSE, &(m_camera->GetView()[0][0]));

	m_snowEmitter->draw(CurrentTime(), m_camera->GetTransform(), m_camera->GetProjectionView());
	//m_terrain->Render(m_camera->GetProjectionView());

	// Light Pass: render lights as geometry, sampling position and
	// normals disable depth testing and enable additive blending
	m_lightPassTarget->SetAsActiveRenderTarget();
	glClear(GL_COLOR_BUFFER_BIT);
	glDisable(GL_DEPTH_TEST);
	glEnable(GL_BLEND);
	glBlendFunc(GL_ONE, GL_ONE);
	
	m_program = IS->UseProgram("Light");

	loc = glGetUniformLocation(m_program, "positionTexture");
	glUniform1i(loc, 0);

	glActiveTexture(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_2D, m_lightPassTarget->GetRenderTexture(0));

	//loc = glGetUniformLocation(m_program, "normalTexture");
	//glUniform1i(loc, 1);

	//glActiveTexture(GL_TEXTURE1);
	//glBindTexture(GL_TEXTURE_2D, m_normalTexture);

	//drawDirectionalLight(m_lightDir, glm::vec3(1, 1, 1));

	glDisable(GL_BLEND);
	glEnable(GL_DEPTH_TEST);

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

	glActiveTexture(GL_TEXTURE1);
	glBindTexture(GL_TEXTURE_2D, 0);

	// Composite Pass: render a quad and combine albedo and light
	glBindFramebuffer(GL_FRAMEBUFFER, 0);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	m_program = IS->UseProgram("Composite");

	loc = glGetUniformLocation(m_program, "albedoTexture");
	glUniform1i(loc, 0);

	glActiveTexture(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_2D, m_gPassTarget->GetRenderTexture(0));

	loc = glGetUniformLocation(m_program, "lightTexture");
	glUniform1i(loc, 1);

	glActiveTexture(GL_TEXTURE1);
	glBindTexture(GL_TEXTURE_2D, m_lightPassTarget->GetRenderTexture(0));

	glBindVertexArray(m_fullscreenQuad);
	glDrawArrays(GL_TRIANGLES, 0, 6);

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

	glActiveTexture(GL_TEXTURE1);
	glBindTexture(GL_TEXTURE_2D, 0);
}
// The MAIN function, from here we start our application and run our Game loop
int main()
{
    // Init GLFW
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

    GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", nullptr, nullptr); // Windowed
    glfwMakeContextCurrent(window);

    // Set the required callback functions
    glfwSetKeyCallback(window, key_callback);
    glfwSetCursorPosCallback(window, mouse_callback);
    glfwSetScrollCallback(window, scroll_callback);

    // Options
    glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);

    // Initialize GLEW to setup the OpenGL Function pointers
    glewExperimental = GL_TRUE;
    glewInit();

    // Define the viewport dimensions
    glViewport(0, 0, SCR_WIDTH, SCR_HEIGHT);

    // Setup some OpenGL options
    glEnable(GL_DEPTH_TEST);

    // Setup and compile our shaders
    Shader shader("parallax_mapping.vs", "parallax_mapping.frag");

    // Load textures
    GLuint diffuseMap = loadTexture("../../../resources/textures/bricks2.jpg");
	GLuint normalMap = loadTexture("../../../resources/textures/bricks2_normal.jpg");
	GLuint heightMap = loadTexture("../../../resources/textures/bricks2_disp.jpg");
    //GLuint diffuseMap = loadTexture("../../../resources/textures/wood.png");
    //GLuint normalMap = loadTexture("../../../resources/textures/toy_box_normal.png");
    //GLuint heightMap = loadTexture("../../../resources/textures/toy_box_disp.png");

    // Set texture units 
    shader.Use();
    glUniform1i(glGetUniformLocation(shader.Program, "diffuseMap"), 0);
	glUniform1i(glGetUniformLocation(shader.Program, "normalMap"), 1);
	glUniform1i(glGetUniformLocation(shader.Program, "depthMap"), 2);

    // Light position
    glm::vec3 lightPos(0.5f, 1.0f, 0.3f);

    // Game loop
    while (!glfwWindowShouldClose(window))
    {
        // Set frame time
        GLfloat currentFrame = glfwGetTime();
        deltaTime = currentFrame - lastFrame;
        lastFrame = currentFrame;

        // Check and call events
        glfwPollEvents();
        Do_Movement();

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

        // Configure view/projection matrices
        shader.Use();
        glm::mat4 view = camera.GetViewMatrix();
        glm::mat4 projection = glm::perspective(camera.Zoom, (GLfloat)SCR_WIDTH / (GLfloat)SCR_HEIGHT, 0.1f, 100.0f);
        glUniformMatrix4fv(glGetUniformLocation(shader.Program, "view"), 1, GL_FALSE, glm::value_ptr(view));
        glUniformMatrix4fv(glGetUniformLocation(shader.Program, "projection"), 1, GL_FALSE, glm::value_ptr(projection));
        // Render normal-mapped quad
        glm::mat4 model;
        model = glm::rotate(model, (GLfloat)glfwGetTime() * -10, glm::normalize(glm::vec3(1.0, 0.0, 1.0))); // Rotates the quad to show parallax mapping works in all directions
        glUniformMatrix4fv(glGetUniformLocation(shader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model));
        glUniform3fv(glGetUniformLocation(shader.Program, "lightPos"), 1, &lightPos[0]);
		glUniform3fv(glGetUniformLocation(shader.Program, "viewPos"), 1, &camera.Position[0]);
		glUniform1f(glGetUniformLocation(shader.Program, "height_scale"), height_scale);
		glUniform1i(glGetUniformLocation(shader.Program, "parallax"), parallax_mapping);
        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, diffuseMap);
        glActiveTexture(GL_TEXTURE1);
        glBindTexture(GL_TEXTURE_2D, normalMap);
		glActiveTexture(GL_TEXTURE2);
		glBindTexture(GL_TEXTURE_2D, heightMap);
        RenderQuad();

        // render light source (simply renders a smaller plane at the light's position for debugging/visualization)
        model = glm::mat4();
        model = glm::translate(model, lightPos);
        model = glm::scale(model, glm::vec3(0.1f));
        glUniformMatrix4fv(glGetUniformLocation(shader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model));
        //RenderQuad();

        // Swap the buffers
        glfwSwapBuffers(window);
    }

    glfwTerminate();
    return 0;
}
Esempio n. 27
0
	GLint ShaderProgram::getUniformLocation(const GLchar *name)
	{
		return glGetUniformLocation(m_program, name);
	}
Esempio n. 28
0
GLUSboolean init(GLUSvoid)
{
    GLfloat* points = (GLfloat*) malloc(WATER_PLANE_LENGTH * WATER_PLANE_LENGTH * 4 * sizeof(GLfloat));
    GLuint* indices = (GLuint*) malloc(WATER_PLANE_LENGTH * (WATER_PLANE_LENGTH - 1) * 2 * sizeof(GLuint));

    GLUStgaimage image;

    GLUStextfile vertexSource;
    GLUStextfile fragmentSource;

    GLuint x, z, i, k;

    GLuint waterTexture;

    for (z = 0; z < WATER_PLANE_LENGTH; z++)
    {
        for (x = 0; x < WATER_PLANE_LENGTH; x++)
        {
            points[(x + z * (WATER_PLANE_LENGTH)) * 4 + 0] = -(GLfloat) WATER_PLANE_LENGTH / 2 + 0.5f + (GLfloat) x;
            points[(x + z * (WATER_PLANE_LENGTH)) * 4 + 1] = 0.0f;
            points[(x + z * (WATER_PLANE_LENGTH)) * 4 + 2] = +(GLfloat) WATER_PLANE_LENGTH / 2 - 0.5f - (GLfloat) z;
            points[(x + z * (WATER_PLANE_LENGTH)) * 4 + 3] = 1.0f;
        }
    }

    for (k = 0; k < WATER_PLANE_LENGTH - 1; k++)
    {
        for (i = 0; i < WATER_PLANE_LENGTH; i++)
        {
            if (k % 2 == 0)
            {
                indices[(i + k * (WATER_PLANE_LENGTH)) * 2 + 0] = i + (k + 1) * WATER_PLANE_LENGTH;
                indices[(i + k * (WATER_PLANE_LENGTH)) * 2 + 1] = i + k * WATER_PLANE_LENGTH;
            }
            else
            {
                indices[(i + k * (WATER_PLANE_LENGTH)) * 2 + 0] = WATER_PLANE_LENGTH - 1 - i + k * WATER_PLANE_LENGTH;
                indices[(i + k * (WATER_PLANE_LENGTH)) * 2 + 1] = WATER_PLANE_LENGTH - 1 - i + (k + 1) * WATER_PLANE_LENGTH;
            }
        }
    }

    //

    glusFileLoadText("../Example15_ES/shader/Water.vert.glsl", &vertexSource);
    glusFileLoadText("../Example15_ES/shader/Water.frag.glsl", &fragmentSource);

    glusProgramBuildFromSource(&g_program, (const GLUSchar**) &vertexSource.text, (const GLUSchar**) &fragmentSource.text);

    glusFileDestroyText(&vertexSource);
    glusFileDestroyText(&fragmentSource);

    //

    g_projectionMatrixLocation = glGetUniformLocation(g_program.program, "u_projectionMatrix");
    g_viewMatrixLocation = glGetUniformLocation(g_program.program, "u_viewMatrix");
    g_inverseViewNormalMatrixLocation = glGetUniformLocation(g_program.program, "u_inverseViewNormalMatrix");

    g_waterPlaneLengthLocation = glGetUniformLocation(g_program.program, "u_waterPlaneLength");

    g_cubemapLocation = glGetUniformLocation(g_program.program, "u_cubemap");

    g_waterTextureLocation = glGetUniformLocation(g_program.program, "u_waterTexture");

    g_passedTimeLocation = glGetUniformLocation(g_program.program, "u_passedTime");

    g_waveParametersLocation = glGetUniformLocation(g_program.program, "u_waveParameters");
    g_waveDirectionsLocation = glGetUniformLocation(g_program.program, "u_waveDirections");

    g_vertexLocation = glGetAttribLocation(g_program.program, "a_vertex");

    //

    glGenBuffers(1, &g_verticesVBO);
    glBindBuffer(GL_ARRAY_BUFFER, g_verticesVBO);
    glBufferData(GL_ARRAY_BUFFER, WATER_PLANE_LENGTH * WATER_PLANE_LENGTH * 4 * sizeof(GLfloat), (GLfloat*) points, GL_STATIC_DRAW);

    glBindBuffer(GL_ARRAY_BUFFER, 0);

    glGenBuffers(1, &g_indicesVBO);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_indicesVBO);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, WATER_PLANE_LENGTH * (WATER_PLANE_LENGTH - 1) * 2 * sizeof(GLuint), (GLuint*) indices, GL_STATIC_DRAW);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

    //

    free(points);
    free(indices);

    //

    glGenTextures(1, &g_cubemap);
    glBindTexture(GL_TEXTURE_CUBE_MAP, g_cubemap);

    glusImageLoadTga("water_pos_x.tga", &image);
    glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0, image.format, image.width, image.height, 0, image.format, GL_UNSIGNED_BYTE, image.data);
    glusImageDestroyTga(&image);

    glusImageLoadTga("water_neg_x.tga", &image);
    glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_X, 0, image.format, image.width, image.height, 0, image.format, GL_UNSIGNED_BYTE, image.data);
    glusImageDestroyTga(&image);

    glusImageLoadTga("water_pos_y.tga", &image);
    glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Y, 0, image.format, image.width, image.height, 0, image.format, GL_UNSIGNED_BYTE, image.data);
    glusImageDestroyTga(&image);

    glusImageLoadTga("water_neg_y.tga", &image);
    glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, 0, image.format, image.width, image.height, 0, image.format, GL_UNSIGNED_BYTE, image.data);
    glusImageDestroyTga(&image);

    glusImageLoadTga("water_pos_z.tga", &image);
    glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Z, 0, image.format, image.width, image.height, 0, image.format, GL_UNSIGNED_BYTE, image.data);
    glusImageDestroyTga(&image);

    glusImageLoadTga("water_neg_z.tga", &image);
    glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, 0, image.format, image.width, image.height, 0, image.format, GL_UNSIGNED_BYTE, image.data);
    glusImageDestroyTga(&image);

    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

    glBindTexture(GL_TEXTURE_CUBE_MAP, 0);

    //

    waterTexture = initWaterTexture((GLUSfloat) WATER_PLANE_LENGTH);

    glUseProgram(g_program.program);

    glUniform1f(g_waterPlaneLengthLocation, (GLUSfloat) WATER_PLANE_LENGTH);

    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_CUBE_MAP, g_cubemap);
    glUniform1i(g_cubemapLocation, 0);

    glActiveTexture(GL_TEXTURE1);
    glBindTexture(GL_TEXTURE_2D, waterTexture);
    glUniform1i(g_waterTextureLocation, 1);

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

    glBindBuffer(GL_ARRAY_BUFFER, g_verticesVBO);
    glVertexAttribPointer(g_vertexLocation, 4, GL_FLOAT, GL_FALSE, 0, 0);
    glEnableVertexAttribArray(g_vertexLocation);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_indicesVBO);

    //

    initBackground();

    //

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

    glClearDepthf(1.0f);

    glEnable(GL_DEPTH_TEST);

    glEnable(GL_CULL_FACE);

    return GLUS_TRUE;
}
Esempio n. 29
0
GLint Program::uniformLocation(const GLchar *name) const
{
	return glGetUniformLocation(m_Id, name);
}
Esempio n. 30
0
void Assignment1::Init()
{
	// Init VBO here
	// Set background color to dark blue
	glClearColor(0.3f, 0.0f, 0.0f, 0.0f);

	// Generate a default VAO for now
	glGenVertexArrays(1, &m_vertexArrayID);
	glBindVertexArray(m_vertexArrayID);
	glGenBuffers(NUM_GEOMETRY, &m_vertexBuffer[0]);
	glGenBuffers(NUM_GEOMETRY, &m_colorBuffer[0]);


	static const GLfloat vertex_buffer_data[] =
	{
		0.0f, 0.0f, 0.0f,
		0.0f, 1.0f, 0.0f,
		1.0f, 0.1f, 0.0f,
	};
	
	glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer[GEO_TRIANGLE_1]);
	glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_buffer_data), vertex_buffer_data, GL_STATIC_DRAW);
	
	static const GLfloat vertex_buffer_data1[] =
	{
		0.0f, 0.0f, 0.0f,
		0.0f, 1.0f, 0.0f,
		1.0f, 1.0f, 0.0f,
	};
	glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer[GEO_TRIANGLE_2]);
	glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_buffer_data1), vertex_buffer_data1, GL_STATIC_DRAW);

	static const GLfloat vertex_buffer_data2[] =
	{
		0.0f, 0.0f, 0.0f,
		0.0f, 1.0f, 0.0f,
		1.0f, 1.0f, 0.0f,
		0.0f, 0.0f, 0.0f,
		1.0f, 0.0f, 0.0f,
		1.0f, 1.0f, 0.0f,
	};
	glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer[GEO_TRIANGLE_3]);
	glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_buffer_data2), vertex_buffer_data2, GL_STATIC_DRAW);
	glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer[GEO_DOOR]);
	glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_buffer_data2), vertex_buffer_data2, GL_STATIC_DRAW);
	glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer[GEO_CLOUD]);
	glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_buffer_data2), vertex_buffer_data2, GL_STATIC_DRAW);

	static const GLfloat vertex_buffer_data3[] =
	{
		-1.0f, 0.0f, 0.0f,
		0.0f, 1.0f, 0.0f,
		1.0f, 0.0f, 0.0f,
	};
	glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer[GEO_BIRD]);
	glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_buffer_data3), vertex_buffer_data3, GL_STATIC_DRAW);

	static const GLfloat color_buffer_data[] =
	{
		1.0f, 0.0f, 0.0f,
		0.0f, 0.0f, 0.0f,
		1.0f, 0.0f, 0.0f,
	};
	glBindBuffer(GL_ARRAY_BUFFER, m_colorBuffer[GEO_TRIANGLE_1]);
	glBufferData(GL_ARRAY_BUFFER, sizeof(color_buffer_data), color_buffer_data, GL_STATIC_DRAW);
	
	static const GLfloat color_buffer_data1[] =
	{
		0.0f, 1.0f, 0.0f,
		0.0f, 1.0f, 0.0f,
		0.0f, 1.0f, 0.0f,
	};
	glBindBuffer(GL_ARRAY_BUFFER, m_colorBuffer[GEO_TRIANGLE_2]);
	glBufferData(GL_ARRAY_BUFFER, sizeof(color_buffer_data1), color_buffer_data1, GL_STATIC_DRAW);

	static const GLfloat color_buffer_data2[] =
	{
		0.0f, 0.0f, 0.0f,
		0.0f, 0.0f, 0.0f,
		1.0f, 0.0f, 0.0f,
		0.0f, 0.0f, 0.0f,
		1.0f, 0.0f, 0.0f,
		1.0f, 0.0f, 0.0f,
	};
	glBindBuffer(GL_ARRAY_BUFFER, m_colorBuffer[GEO_TRIANGLE_3]);
	glBufferData(GL_ARRAY_BUFFER, sizeof(color_buffer_data2), color_buffer_data2, GL_STATIC_DRAW);

	static const GLfloat color_buffer_data3[] =
	{
		1.0f, 0.0f, 0.0f,
		1.0f, 0.0f, 0.0f,
		1.0f, 1.0f, 1.0f,
		1.0f, 0.0f, 0.0f,
		1.0f, 1.0f, 1.0f,
		1.0f, 1.0f, 1.0f,
	};
	glBindBuffer(GL_ARRAY_BUFFER, m_colorBuffer[GEO_DOOR]);
	glBufferData(GL_ARRAY_BUFFER, sizeof(color_buffer_data3), color_buffer_data3, GL_STATIC_DRAW);

	static const GLfloat color_buffer_data4[] =
	{
		0.0f, 0.0f, 0.0f,
		0.0f, 0.0f, 0.0f,
		0.0f, 0.0f, 0.0f,
	};
	glBindBuffer(GL_ARRAY_BUFFER, m_colorBuffer[GEO_BIRD]);
	glBufferData(GL_ARRAY_BUFFER, sizeof(color_buffer_data4), color_buffer_data4, GL_STATIC_DRAW);

	static const GLfloat color_buffer_data5[] =
	{
		0.5f, 0.5f, 0.5f,
		0.5f, 0.5f, 0.5f,
		0.0f, 0.0f, 0.0f,
		0.5f, 0.5f, 0.5f,
		0.0f, 0.0f, 0.0f,
		0.0f, 0.0f, 0.0f,
	};
	glBindBuffer(GL_ARRAY_BUFFER, m_colorBuffer[GEO_CLOUD]);
	glBufferData(GL_ARRAY_BUFFER, sizeof(color_buffer_data5), color_buffer_data5, GL_STATIC_DRAW);

	for (int i = 0; i < 100; i++)
	{
		rainpositionx[i] = rand() % 80 - 40;
		rainpositiony[i] = rand() % 60 - 30;
	}
	//Load vertex and fragment shaders
	m_programID = LoadShaders(
		"Shader//TransformVertexShader.vertexshader",
		"Shader//SimpleFragmentShader.fragmentshader");
	m_parameters[U_MVP] = glGetUniformLocation(m_programID, "MVP");
	glUseProgram(m_programID);
	glEnable(GL_DEPTH_TEST);

	rotateAngle = 0.0f;
	translateX = 1;
	translateX2 = 1;
	translateY = 30;
	scaleAll = 10;
}