Example #1
0
  void onFrame() {

    if (camera.isTransformed) {
      camera.transform();
    }

    glViewport(0, 0, width, height);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    cmt.bind(GL_TEXTURE0); {

      skyboxProgram.bind(); {
        glUniformMatrix4fv(skyboxProgram.uniform("view"), 1, 0, ptr(camera.view));
        glUniformMatrix4fv(skyboxProgram.uniform("proj"), 1, 0, ptr(camera.projection));
        glUniform1i(skyboxProgram.uniform("cube_texture"), 0);

        skyboxMeshBuffer.draw();
      } skyboxProgram.unbind();

      vec3 totals = rotateBehavior.tick(now()).totals();
      cubeModel = glm::mat4();
      cubeModel = glm::translate(cubeModel, vec3(12.0,0.0,40.0));
      cubeModel = glm::rotate(cubeModel, totals.x, vec3(1.0f,0.0f,0.0f));
      cubeModel = glm::rotate(cubeModel, totals.y, vec3(0.0f,1.0f,0.0f));

      dragonModel = glm::mat4();
      dragonModel = glm::translate(dragonModel, vec3(-12.0,-15.0,40.0));
      dragonModel = glm::rotate(dragonModel, totals.y, vec3(0.0f,1.0f,0.0f));


      environmentMappingProgram.bind(); {
        glUniformMatrix4fv(environmentMappingProgram.uniform("view"), 1, 0, ptr(camera.view));
        glUniformMatrix4fv(environmentMappingProgram.uniform("proj"), 1, 0, ptr(camera.projection));
        glUniform1i(environmentMappingProgram.uniform("cube_texture"), 0);

        //set dragon specific variables and draw dragon
        glUniformMatrix4fv(environmentMappingProgram.uniform("model"), 1, 0, ptr(dragonModel));
        glUniform4f(environmentMappingProgram.uniform("baseColor"), 0.0, 0.0, 0.1, 1.0);
        dragonMeshBuffer.draw();

        //set cube specific variables and draw cube
        glUniformMatrix4fv(environmentMappingProgram.uniform("model"), 1, 0, ptr(cubeModel));
        glUniform4f(environmentMappingProgram.uniform("baseColor"), 0.1, 0.0, 0.0, 1.0);
        cubeMeshBuffer.draw();
      } environmentMappingProgram.unbind();

    } cmt.unbind(GL_TEXTURE0);

  }
	virtual	void	redisplay ()
	{
		static	GLuint	buf [] = { 0, 0, 0, 0 };
		static	GLuint	counters [4];
		
		counterBuf.setData ( sizeof ( buf ), buf, GL_DYNAMIC_DRAW );
		
		glClear ( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

		mat4	mv = mat4 :: rotateZ ( toRadians ( rot.z ) ) * mat4 :: rotateY ( toRadians ( rot.y ) ) * mat4 :: rotateX ( toRadians ( rot.x ) );
		mat3	nm = normalMatrix ( mv );
		
		program.bind ();
		program.setUniformMatrix ( "mv",  mv );
		program.setUniformMatrix ( "nm",  nm );

		mesh -> render ();

		program.unbind ();
		
		glFinish ();
		
		counterBuf.getSubData ( 0, sizeof ( buf ), counters );
		
		printf ( "%4d %4d %d %d\n", counters [0], counters [1], counters [2], counters [3] );
	}
Example #3
0
	MyCaveGeneratorTestLoop(Window *w) : SDLLoop(w) 
	{
		cout << "Initializing glew\n";
		glewInit();

		cout << "Binding program\n";
		program.addShader(Shader(GL_VERTEX_SHADER, "functional/phong/shader.vp"));
		program.addShader(Shader(GL_FRAGMENT_SHADER, "functional/phong/shader.fp"));
		program.link();
		program.bind();
		
		cout << "Getting locations of shader parameters\n";
		vertexLocation = program.getAttributeLocation("vPosition");
		texCoordLocation = program.getAttributeLocation("uv");
		vertexColorLocation = program.getAttributeLocation("vColor");
		samplerLocation = program.getUniformLocation("image");
		modelLocation = program.getUniformLocation("model");
		perspectiveLocation= program.getUniformLocation("perspective");
		normalLocation = program.getAttributeLocation("Normal");
		ambientProductLocation = program.getUniformLocation("ambientProduct");
		diffuseProductLocation = program.getUniformLocation("diffuseProduct");
		specularProductLocation = program.getUniformLocation("specularProduct");
		lightPositionLocation = program.getUniformLocation("LightPosition");
		shininessLocation = program.getUniformLocation("shininess");
		
		program.enableAttributeArray(vertexLocation);
		program.enableAttributeArray(texCoordLocation);
		program.enableAttributeArray(vertexColorLocation);
		program.enableAttributeArray(normalLocation);
		
		signal = new PerlinSignal;
		signal->addFrequency(2, 0.2);
		signal->addFrequency(16, 0.01);
	}
	//onFrame syncs with the refresh rate of the display (e.g., 60fps). Here we can send information to the GPU to define exactly how the pixels on the window should look.
	virtual void onFrame(){

		glViewport(0, 0, width, height); //defines the active viewport to match the size of our window
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // clears color and depth info from the viewport
		glEnable(GL_DEPTH_TEST);
		glDisable(GL_BLEND);

		//have the pyramid to rotate in place
		m = glm::rotate(m, rx, vec3(1.0f, 0.0f, 0.0f));
		m = glm::rotate(m, ry, vec3(0.0f, 1.0f, 0.0f));

		//update the view matrix based on the camera's rotation
		v = mat4(1.0); //reset to identity
		v = glm::rotate(v, cx, vec3(1.0f, 0.0f, 0.0f)); //rotate sum amount around the x-axis
		v = glm::rotate(v, cy, vec3(0.0f, 1.0f, 0.0f)); //rotate sum amount around the y-axis
		v = glm::translate(v, vec3(0, 0, pz)); //translate the "cursor" forward five units ( = move the camera five units backwards)


		// the program.bind() activates our shader program so that we can 1. pass data to it and 2. let it draw to the active viewport in our window
		program.bind(); {

			glUniformMatrix4fv(program.uniform("m"), 1, 0, ptr(m)); //pass in the model matrix
			glUniformMatrix4fv(program.uniform("v"), 1, 0, ptr(v)); //pass in the view matrix
			glUniformMatrix4fv(program.uniform("p"), 1, 0, ptr(p)); //pass in the projection matrix

			glBindVertexArray(vao); //binds our vertex array object, containing all our data and information about how it's organized and indexed
			glDrawElements(GL_TRIANGLES, 12, GL_UNSIGNED_INT, BUFFER_OFFSET(0)); //passes the entire data buffer to the GPU as a set of triangles; that is, read the index array three items at a time.

			glBindVertexArray(0);
		} program.unbind();

	}
 void onFrame(){
   
   model = glm::mat4(1.0);
   
   vec3 totals = rotateBehavior.tick(now()).totals();
   model = glm::rotate(model, totals.x, vec3(1.0f,0.0f,0.0f));
   model = glm::rotate(model, totals.y, vec3(0.0f,1.0f,0.0f));
   model = glm::rotate(model, totals.z, vec3(0.0f,0.0f,1.0f));
   
   
   //draw cube 1 into an offscreen texture
   fbo.bind(); {
     glViewport(0, 0, fbo.width, fbo.height);
     glClearColor(0.1,0.1,0.1,1.0);
     glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
     
     draw(model, cubeMeshBuffer1, texture, textureProgram);
     
   } fbo.unbind();
   
   
   //draw cube 2 with the offscreen texture using phong shading
   glViewport(0, 0, width, height);
   glClearColor(0.0,0.0,0.0,1.0);
   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
   
   model = glm::mat4(1.0);
   
   model = glm::translate(model, vec3(1.0,0.0,0.0));
   model = glm::rotate(model, totals.x, vec3(1.0f,0.0f,0.0f));
   model = glm::rotate(model, totals.y, vec3(0.0f,1.0f,0.0f));
   model = glm::rotate(model, totals.z, vec3(0.0f,0.0f,1.0f));
   
   draw(model, cubeMeshBuffer2, fbo.texture, phongProgram);
   
   
   
   //draw cube 3 - a colored cube
   
   model = mat4(1.0);
   model = glm::translate(model, vec3(-1.0,0.0,0.0));
   
   model = glm::rotate(model, -totals.x, vec3(1.0f,0.0f,0.0f));
   model = glm::rotate(model, -totals.y, vec3(0.0f,1.0f,0.0f));
   model = glm::rotate(model, -totals.z, vec3(0.0f,0.0f,1.0f));
   
   programColor.bind(); {
     glUniformMatrix4fv(programColor.uniform("model"), 1, 0, ptr(model));
     glUniformMatrix4fv(programColor.uniform("view"), 1, 0, ptr(view));
     glUniformMatrix4fv(programColor.uniform("proj"), 1, 0, ptr(proj));
     
     cubeMeshBuffer3.draw();
     
   } programColor.unbind();
   
 }
Example #6
0
 void uploadFullscreenQuad(const Program & sp) {
     sp.bind();
     float quad[] = {
         -1.0f,  1.0f, 0.0f, 1.0f,	// top left corner
         -1.0f, -1.0f, 0.0f, 0.0f,	// bottom left corner
          1.0f,  1.0f, 1.0f, 1.0f,// top right corner
          1.0f, -1.0f, 1.0f, 0.0f	// bottom right corner
     };
     sp.uploadData(quad, sizeof(quad));
 }
Example #7
0
void PrimitiveShape::paint()
{
    VertexBuffer* vb = m_vertexbuffer;
    // IndexBuffer* ib = m_indexbuffer;
    Program* pr = m_program;
    if( !vb || !pr )
    {
        return;
    }
    size_t vertexcount;
    VertexDeclaration* vdecl;
    if( !vb->bind( &vertexcount, &vdecl ) )
    {
        return;
    }
    // int indexcount;
    // if( ib )
    // {
    // if( !ib->bind( &indexcount ) )
    // {
    // return;
    // }
    // }
    if( !pr->bind() )
    {
        return;
    }
    int ptype = m_type.load( std::memory_order_acquire );
    checkerror( Context::Device->SetRenderState(
                    D3DRS_BLENDOP, m_blendop ) );
    checkerror( Context::Device->SetRenderState(
                    D3DRS_SRCBLEND, m_blendsf ) );
    checkerror( Context::Device->SetRenderState(
                    D3DRS_DESTBLEND, m_blenddf ) );
    {
        lock_t lock( m_mutex );
        checkerror( Context::Device->SetVertexShaderConstantF(
                        0, m_matrix.m[ 0 ], 4 ) );
    }
    // checkerror( Context::Device->DrawIndexedPrimitive(
    // D3DPRIMITIVETYPE( m_type ),
    // 0,
    // 0,
    // vertexcount,
    // 0,
    // indexcount / 3 ) );
    checkerror( Context::Device->DrawPrimitive(
                    D3DPRIMITIVETYPE( typetable[ ptype ] ),
                    0,
                    UINT( ( vertexcount - poffsettable[ ptype ] )
                          / pfactortable[ ptype ] ) ) );
}
	virtual	void	reshape ( int w, int h )
	{
		GlutWindow::reshape ( w, h );
		
		glViewport ( 0, 0, (GLsizei)w, (GLsizei)h );
	   
		mat4 proj = perspective ( 60.0f, (float)w / (float)h, 0.5f, 20.0f ) * lookAt ( eye, vec3 :: zero, vec3 ( 0, 0, 1 ) );

		program.bind ();
		program.setUniformMatrix ( "proj",  proj );
		program.setUniformVector ( "eye",   eye );
		program.setUniformVector ( "light", light );
		program.unbind ();  
	}
Example #9
0
void bind_prog_and_attributes(const VertexFormat& vf, const Program& program)
{
	program.bind();

	for (auto&& vc : vf) {
		const auto attrib_loc = program.get_attribute_loc(vc.name);

		CHECK_FOR_GL_ERROR;
		glEnableVertexAttribArray(attrib_loc);
		CHECK_FOR_GL_ERROR;
		glVertexAttribPointer(attrib_loc, vc.num_comps, vc.type, vc.normalize, (GLsizei)vf.stride(), (const void*)vc.offset);
		CHECK_FOR_GL_ERROR;
	}
}
Example #10
0
	virtual	void	idle () 
	{
		angle  = 4 * getTime ();

		light.x = 8*cos ( angle );
		light.y = 8*sin ( 1.4 * angle );
		light.z = 8 + 0.5 * sin ( angle / 3 );

		program.bind ();
		program.setUniformVector ( "eye",   eye   );
		program.setUniformVector ( "light", light );
		program.unbind ();

		GlutWindow::idle ();		// for glutPostRedisplay ();
	}
Example #11
0
 void draw(mat4& model, MeshBuffer& mb, Texture& t, Program& p) {
   
   p.bind(); {
     glUniformMatrix4fv(p.uniform("model"), 1, 0, ptr(model));
     glUniformMatrix4fv(p.uniform("view"), 1, 0, ptr(view));
     glUniformMatrix4fv(p.uniform("proj"), 1, 0, ptr(proj));
     
     t.bind(GL_TEXTURE0); {
       
       glUniform1i(p.uniform("tex0"), 0);
       mb.draw();
       
     } t.unbind(GL_TEXTURE0);
     
   } p.unbind();
 }
	MyArray3DLayeredHeightfieldTestLoop(Window *w) : SDLLoop(w) 
	{
		cout << "Initializing glew\n";
		glewInit();

		cout << "Binding program\n";
		program.addShader(Shader(GL_VERTEX_SHADER, "functional/phong/shader.vp"));
		program.addShader(Shader(GL_FRAGMENT_SHADER, "functional/phong/shader.fp"));
		program.link();
		program.bind();
		
		cout << "Getting locations of shader parameters\n";
		vertexLocation = program.getAttributeLocation("vPosition");
		texCoordLocation = program.getAttributeLocation("uv");
		vertexColorLocation = program.getAttributeLocation("vColor");
		samplerLocation = program.getUniformLocation("image");
		modelLocation = program.getUniformLocation("model");
		perspectiveLocation= program.getUniformLocation("perspective");
		normalLocation = program.getAttributeLocation("Normal");
		ambientProductLocation = program.getUniformLocation("ambientProduct");
		diffuseProductLocation = program.getUniformLocation("diffuseProduct");
		specularProductLocation = program.getUniformLocation("specularProduct");
		lightPositionLocation = program.getUniformLocation("LightPosition");
		shininessLocation = program.getUniformLocation("shininess");
		
		program.enableAttributeArray(vertexLocation);
		program.enableAttributeArray(texCoordLocation);
		program.enableAttributeArray(vertexColorLocation);
		program.enableAttributeArray(normalLocation);
		
		signal = new PerlinSignal;
		signal->addFrequency(2, 0.5);
		signal->addFrequency(16, 0.01);
		generator = new MyLayeredVoxeledHeightfield(signal);

		voxels = new Array3D<bool>(128, 128, 128);
		generator->populateArray(voxels, 128);
		
		for (int j = 0; j<5; j++) make_hole(*voxels);
		for (int i =0; i<10; i++) (*voxels).copy(erode(*voxels));
		
		adapter = new Array3DLayeredHeightfieldAdapter(*voxels);
		adapter->generate();
		h = adapter->getField();
		cout << "Number of levels " << h->levelCount() << endl;

	}
Example #13
0
	void PrimitiveShape::paint()
	{
		VertexBuffer* vb = m_vertexbuffer;
		// IndexBuffer* ib = m_indexbuffer;
		Program* pr = m_program;
		if( !vb || !pr )
		{
			return;
		}
		size_t vertexcount;
		VertexDeclaration* vdecl;
		if( !vb->bind( &vertexcount, &vdecl ) )
		{
			return;
		}
		// int indexcount;
		// if( ib )
		// {
			// if( !ib->bind( &indexcount ) )
			// {
				// return;
			// }
		// }
		int worldmatrixpos;
		if( !pr->bind( &worldmatrixpos ) )
		{
			return;
		}
		int ptype = m_type.load( std::memory_order_acquire );
		glBlendEquation( m_blendop );
		checkerror();
		glBlendFunc( m_blendsf, m_blenddf );
		checkerror();
		if( worldmatrixpos != -1 )
		{
			lock_t lock( m_mutex );
			glUniformMatrix4fv( worldmatrixpos, 1, false, m_matrix );
		}
		// checkerror( Context::Device->DrawIndexedPrimitive(
			// D3DPRIMITIVETYPE( m_type ),
			// 0,
			// 0,
			// vertexcount,
			// 0,
			// indexcount / 3 ) );
		glDrawArrays( typetable[ ptype ], 0, GLsizei( vertexcount ) );
	}
Example #14
0
	MyVoxeledTerrainTestLoop(Window *w) : SDLLoop(w) 
	{
		cout << "Initializing glew\n";
		glewInit();

		cout << "Binding program\n";
		program.addShader(Shader(GL_VERTEX_SHADER, "functional/scene/shader.vp"));
		program.addShader(Shader(GL_FRAGMENT_SHADER, "functional/scene/shader.fp"));
		program.link();
		program.bind();
		
		cout << "Getting locations of shader parameters\n";
		vertexLocation = program.getAttributeLocation("vPosition");
		texCoordLocation = program.getAttributeLocation("uv");
		vertexColorLocation = program.getAttributeLocation("vColor");
		samplerLocation = program.getUniformLocation("image");
		modelLocation = program.getUniformLocation("model");
		perspectiveLocation= program.getUniformLocation("perspective");
		normalLocation = program.getAttributeLocation("Normal");
		ambientProductLocation = program.getUniformLocation("ambientProduct");
		diffuseProductLocation = program.getUniformLocation("diffuseProduct");
		specularProductLocation = program.getUniformLocation("specularProduct");
		lightPositionLocation = program.getUniformLocation("LightPosition");
		shininessLocation = program.getUniformLocation("shininess");
		
		cout <<  program.getAttributeLocation("vPosition")<< endl;
		cout <<  program.getAttributeLocation("uv")<< endl;
		cout <<  program.getAttributeLocation("vColor")<< endl;
		cout <<  program.getUniformLocation("image")<< endl;
		cout <<  program.getUniformLocation("model")<< endl;
		cout <<  program.getUniformLocation("perspective")<< endl;
		cout <<  program.getAttributeLocation("Normal")<< endl;
		cout <<  program.getUniformLocation("ambientProduct")<< endl;
		cout <<  program.getUniformLocation("diffuseProduct")<< endl;
		cout <<  program.getUniformLocation("specularProduct")<< endl;
		cout <<  program.getUniformLocation("LightPosition")<< endl;
		cout <<  program.getUniformLocation("shininess")<< endl;
		
		cout << "Normal location: " << normalLocation << endl;

		program.enableAttributeArray(vertexLocation);
		program.enableAttributeArray(texCoordLocation);
		program.enableAttributeArray(vertexColorLocation);
		program.enableAttributeArray(normalLocation);
	}
Example #15
0
    void onFrame(){

      glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

      program.bind(); {

	glUniformMatrix4fv(program.uniform("model"), 1, 0, ptr(model));
	glUniformMatrix4fv(program.uniform("view"), 1, 0, ptr(view));
	glUniformMatrix4fv(program.uniform("proj"), 1, 0, ptr(proj));

	glUniform1f(program.uniform("bloom"), bloomAmt);
	glUniform1i(program.uniform("tex0"), 0);

	texture.bind(GL_TEXTURE0); {
	  mb1.draw();	
	} texture.unbind(GL_TEXTURE0);

      } program.unbind();
    }
Example #16
0
  void onFrame() {

    float ratio = float(height) / float(width);
    float c = cosf(angle);
    float s = sinf(angle);

    vec4 rot = scale * vec4(c, -s * ratio, s, c * ratio);

    planetProgram.bind(); {
      glUniform4fv(planetProgram.uniform("rot"), 1, ptr(rot));
      glUniform1f(planetProgram.uniform("zoom"), zoom);
      glUniform1f(planetProgram.uniform("power"), power);
      glUniform1i(planetProgram.uniform("cube_texture"), 0);

      cubemap[which].bind(GL_TEXTURE0); {
        mb.draw();
      } cubemap[which].unbind(GL_TEXTURE0);

    } planetProgram.unbind();
  }
  void onFrame() {

    val += 0.01;

    glViewport(0, 0, width, height);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

   // updateModel();

    program.bind(); {
      glUniformMatrix4fv(program.uniform("model"), 1, 0, ptr(model));
      glUniformMatrix4fv(program.uniform("view"), 1, 0, ptr(view));
      glUniformMatrix4fv(program.uniform("proj"), 1, 0, ptr(proj));

      glUniform1f(program.uniform("in_val"), val);

      mb.draw();

    } program.unbind();
  }
Example #18
0
  void onFrame(){


    if (camera.isTransformed) { //i.e. if you've pressed any of the keys to move or rotate the camera around
      camera.transform();
    }


    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    program.bind(); {

      glUniformMatrix4fv(program.uniform("model"), 1, 0, ptr(model));
      glUniformMatrix4fv(program.uniform("view"), 1, 0, ptr(camera.view));
      glUniformMatrix4fv(program.uniform("proj"), 1, 0, ptr(camera.projection));

      texture.bind(GL_TEXTURE0); {
        mb1.drawPoints();
      } texture.unbind(GL_TEXTURE0);

    } program.unbind();
  }
Example #19
0
int main(void)
{
    GLFWwindow* window;

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

    // Activate supersampling
    glfwWindowHint(GLFW_SAMPLES, 8);

    // Ensure that we get at least a 3.2 context
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);

    // On apple we have to load a core profile with forward compatibility
#ifdef __APPLE__
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif

    // Create a windowed mode window and its OpenGL context
    window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        return -1;
    }

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

    #ifndef __APPLE__
      glewExperimental = true;
      GLenum err = glewInit();
      if(GLEW_OK != err)
      {
        /* Problem: glewInit failed, something is seriously wrong. */
       fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
      }
      glGetError(); // pull and savely ignonre unhandled errors like GL_INVALID_ENUM
      fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));
    #endif

    int major, minor, rev;
    major = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR);
    minor = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR);
    rev = glfwGetWindowAttrib(window, GLFW_CONTEXT_REVISION);
    printf("OpenGL version recieved: %d.%d.%d\n", major, minor, rev);
    printf("Supported OpenGL is %s\n", (const char*)glGetString(GL_VERSION));
    printf("Supported GLSL is %s\n", (const char*)glGetString(GL_SHADING_LANGUAGE_VERSION));

    // Initialize the VAO
    // A Vertex Array Object (or VAO) is an object that describes how the vertex
    // attributes are stored in a Vertex Buffer Object (or VBO). This means that
    // the VAO is not the actual object storing the vertex data,
    // but the descriptor of the vertex data.
    VertexArrayObject VAO;
    VAO.init();
    VAO.bind();

    // Initialize the VBO with the vertices data
    // A VBO is a data container that lives in the GPU memory
    VBO.init();

    V.resize(2,6);
    V <<
    0,  0.5, -0.5, 0.1,  0.6, -0.4,
    0.5, -0.5, -0.5, 0.6, -0.4, -0.4;
    VBO.update(V);

    // Initialize the OpenGL Program
    // A program controls the OpenGL pipeline and it must contains
    // at least a vertex shader and a fragment shader to be valid
    Program program;
    const GLchar* vertex_shader =
            "#version 150 core\n"
                    "in vec2 position;"
                    "void main()"
                    "{"
                    "    gl_Position = vec4(position, 0.0, 1.0);"
                    "}";
    const GLchar* fragment_shader =
            "#version 150 core\n"
                    "out vec4 outColor;"
                    "uniform vec4 triangleColor;"
                    "void main()"
                    "{"
                    "    outColor = vec4(triangleColor);"
                    "}";

    // Compile the two shaders and upload the binary to the GPU
    // Note that we have to explicitly specify that the output "slot" called outColor
    // is the one that we want in the fragment buffer (and thus on screen)
    program.init(vertex_shader,fragment_shader,"outColor");
    program.bind();

    // The vertex shader wants the position of the vertices as an input.
    // The following line connects the VBO we defined above with the position "slot"
    // in the vertex shader
    program.bindVertexAttribArray("position",VBO);

    // Register the keyboard callback
    glfwSetKeyCallback(window, key_callback);

    // Register the mouse callback
    glfwSetMouseButtonCallback(window, mouse_button_callback);

    // Update viewport
    glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);

    // Loop until the user closes the window
    while (!glfwWindowShouldClose(window))
    {
        // Bind your VAO (not necessary if you have only one)
        VAO.bind();

        // Bind your program
        program.bind();

        // Clear the framebuffer
        glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

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

        // Draw a triangle (red)
        glUniform4f(program.uniform("triangleColor"), 1.0f, 0.0f, 0.0f, 1.0f);
        glDrawArrays(GL_TRIANGLES, 0, 3);

        // Draw a triangle (green)
        glUniform4f(program.uniform("triangleColor"), 0.0f, 1.0f, 0.0f, 0.5f);
        glDrawArrays(GL_TRIANGLES, 3, 3);

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

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

    // Deallocate opengl memory
    program.free();
    VAO.free();
    VBO.free();

    // Deallocate glfw internals
    glfwTerminate();
    return 0;
}
Example #20
0
void OpenGL3Impl::renderMesh(const model::ViewPort& viewPort,
                             model::Entity* cameraEntity,
                             model::Mesh* mesh,
                             model::Material* material,
                             const Transform& transform) {
    Program* program = nullptr;
    model::Material* defaultMaterial = MaterialFactory::getDefault();

    // Make sure we have the render data
    if (mesh->renderData.is_null()) {
        mesh->renderData = ImplData();
    }
    ImplData* data = &mesh->renderData.as<ImplData>();
    data->createFrom(mesh);

    // Let's keep the default material compiled
    buildMaterial(defaultMaterial);

    // Get the camera from the camera entity
    model::Camera* camera = cameraEntity->findComponent<model::Camera>();

    // Resolve the material to use for rendering
    if (material == nullptr) {
        material = defaultMaterial;
    }
    else {
        buildMaterial(material);
    }

    // Resolve the program to use for rendering
    program = material->program;
    if (program == nullptr) {
        program = defaultMaterial->program;
    }

    if (camera != nullptr && material != nullptr && program != nullptr) {
        glViewport(viewPort.x, viewPort.y, viewPort.width, viewPort.height);

        Matrix lookAt = Transform2Matrix(invert(cameraEntity->getTransform()));
        Matrix mat = Transform2Matrix ( transform );
        Matrix matNormals = MatrixForNormals ( mat );
        Matrix matProjection = camera->getProjection();
        if (mPicking) {
            //matProjection = mPickingMatrix * camera->getProjection();
        }

        Matrix matGeometry = matProjection * lookAt * mat;
        Vector3 viewVector = Vector3(0.0f, 1.0f, 0.0) * lookAt;

        program->bind();

        // Set the uniforms
        program->setUniform("un_ProjectionMatrix", matProjection);
        program->setUniform("un_LookatMatrix", lookAt );
        program->setUniform("un_ModelviewMatrix", mat);
        program->setUniform("un_NormalMatrix", matNormals);
        program->setUniform("un_Matrix", matGeometry);
        program->setUniform("un_ViewVector", viewVector);

        GLenum polyType = GL_INVALID_ENUM;
        switch ( mesh->type )
        {
        case model::Mesh::TRIANGLES:
            polyType = GL_TRIANGLES;
            break;
        default:
            break;
        }

        if (polyType != GL_INVALID_ENUM) {
            int textureLevels = 0;
            if (material->texture != nullptr) {
                textureLevels++;
                glActiveTexture(GL_TEXTURE0);
                program->setUniform("un_Sampler0", 0);
                material->texture->bind();

                if (material->texture1 != nullptr) {
                    textureLevels++;
                    glActiveTexture(GL_TEXTURE1);
                    program->setUniform("un_Sampler1", 1);
                    material->texture1->bind();

                    if (material->texture2 != nullptr) {
                        textureLevels++;
                        glActiveTexture(GL_TEXTURE2);
                        program->setUniform("un_Sampler2", 2);
                        material->texture2->bind();
                    }
                }
            }
            program->setUniform("un_TextureLevels", (float)textureLevels);

            program->setUniform("un_Material.diffuse", material->diffuse, true);
            if (material->shadeless == false) {
                program->setUniform("un_Material.ambient", material->ambient, false);
                program->setUniform("un_Material.specular", material->specular, false);
                program->setUniform("un_Material.emission", material->emission, false);
                program->setUniform("un_Material.shininess", material->shininess);
            }
            program->setUniform("un_Material.isShadeless", material->shadeless);

            // For now, hardcode the light values
            program->setUniform("un_Light.diffuse", Color::WHITE, false);
            program->setUniform("un_Light.ambient", Color(80, 80, 80, 255), false);
            program->setUniform("un_Light.specular", Color::WHITE, false);
            program->setUniform("un_Light.position", Vector3(0, 0, 1) );
            program->setUniform("un_Light.direction", Vector3(0.1f, 0, -1) );

            data->bind(program, material->texture != nullptr);
            glDrawElements ( polyType, mesh->indexCount, GL_UNSIGNED_INT, 0 );
            eglGetError();
        }

        program->unbind();
    }

    glUseProgram(0);
}
Example #21
0
 void postexAttrs(const Program & sp) {
     sp.bind();
     sp.addAttrib("position", 2, 4, 0);
     sp.addAttrib("texcoord", 2, 4, 2);
 }
Example #22
0
 void posAttrs(const Program & sp) {
     sp.bind();
     sp.addAttrib("position", 2, 2, 0);
 }