Exemple #1
1
int main()
{
	_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);

	// =======================================================
	//                   INITIALIZE
	// =======================================================
	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, "OpenGl Program", nullptr, nullptr);
	if (window == nullptr)
	{
		printf("Failed to create GLFW window\n");
		glfwTerminate();
		return false;
	}
	glfwMakeContextCurrent(window);

	glewExperimental = GL_TRUE;
	if (glewInit() != GLEW_OK)
	{
		printf("Failed to initialize GLEW\n");
		return false;
	}

	glViewport(0, 0, WIDTH, HEIGHT);
	glEnable(GL_DEPTH_TEST);

	glfwSetKeyCallback(window, Key_callback);
	glfwSetCursorPosCallback(window, mouse_callback);
	glfwSetScrollCallback(window, scroll_callback);


	// Build and compile our shader program
	Shader lightingShader("../Data/Shaders/vertexShaderLighting_nano.vs",
		"../Data/Shaders/fragmentShaderLighting_nano.frag", 2);

	Shader lampShader("../Data/Shaders/vertexShaderLighting_Lamp.vs",
		"../Data/Shaders/fragmentShaderLighting_Lamp.frag", 0);

	// set the application to capture the cursor
	glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);

	glm::vec3 pointLightPositions[] =
	{
		glm::vec3(2.0f, 0.0f, 2.0f),
		glm::vec3(-2.0f, 0.0f, -2.0f),
	};



	DirLight dirlight(lightingShader, vect3(-0.2f, -1.0f, -0.3f), vect3(255, 255, 255), 0.5f);
	PointLight pointLight1(lightingShader, pointLightPositions[0], vect3(255, 255, 255), 0.5f);
	PointLight pointLight2(lightingShader, pointLightPositions[1], vect3(255, 255, 255), 0.5f);
	//PointLight pointLight3(lightingShader, pointLightPositions[2], vect3(255, 255, 255), 1.0f);
	//PointLight pointLight4(lightingShader, pointLightPositions[3], vect3(255, 255, 255), 1.0f);
	SpotLight spotLight(lightingShader, MainCamera.Position, MainCamera.Front, vect3(255, 255, 255), 1.0f);

	GLfloat time = glfwGetTime();
	Model nanosuit("../Data/Models/Box/OutPutModel.txt");
	time = glfwGetTime() - time;
	printf("Time to load: %f", time);

	nanosuit.SetPosition(glm::vec3(0.0f, 0.0f, 0.0f));
	
	// =======================================================
	//                  MAIN UPDATE LOOP
	// =======================================================
	//float count = 0;
	//GLfloat time = 0;

	while (!glfwWindowShouldClose(window))
	{

		// Update deltaTime
		GLfloat currentFrame = glfwGetTime();
		deltaTime = currentFrame - lastFrame;
		lastFrame = currentFrame;

		// FPS check
		//if (time >= 1.0f)
		//{
		//	printf("FPS: %f", count);
		//	time = 0;
		//	count = 0;
		//}

		// check and call events
		glfwPollEvents();
		UpdateCamera();

		// Rendering commands here
		//glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
		glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		// draw triangle
		lightingShader.Use();

		GLint viewPosLoc = lightingShader.GetUniformLocation("viewPos");
		glUniform3f(viewPosLoc, MainCamera.Position.x, MainCamera.Position.y, MainCamera.Position.z);

		// Directional light
		dirlight.Update();

		// Point lights		
		pointLight1.Update(0);
		pointLight2.Update(1);

		// SpotLight
		spotLight.SetPosDir(MainCamera.Position, MainCamera.Front);
		spotLight.Update();

		// Camera/View transformation
		glm::mat4 view;
		view = MainCamera.GetViewMatrix();

		// set the projection matrix (perspective)
		glm::mat4 projectionMatrix;

		// FOV, aspect ratio, near plane, far plane
		projectionMatrix = glm::perspective(glm::radians(MainCamera.Zoom), (GLfloat)WIDTH / (GLfloat)HEIGHT, 0.1f, farPlane);

		// specify matrices
		GLint modelLoc = lightingShader.GetUniformLocation("modelMat");

		GLint viewLoc = lightingShader.GetUniformLocation("viewMat");
		glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));

		GLint projLoc = lightingShader.GetUniformLocation("projectionMat");
		glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projectionMatrix));		

		//glm::mat4 model;
		//model = glm::translate(model, glm::vec3(0, -1.75f, 0.0f)); // Translate it down a bit so it's at the center of the scene
		//model += glm::translate(model, glm::vec3(0.2f, 0.0f, 0.0f));
		//model = glm::scale(model, glm::vec3(0.2f, 0.2f, 0.2f));	// It's a bit too big for our scene, so scale it down
		//glUniformMatrix4fv(glGetUniformLocation(lightingShader.Program, "modelMat"), 1, GL_FALSE, glm::value_ptr(model));

		nanosuit.Draw(lightingShader);

		
		// Swap the buffers
		glfwSwapBuffers(window);
	}

	// =======================================================
	//                     CLEANUP
	// =======================================================
	
	glfwTerminate();
	return 0;
}
void LightingTechnique::SetWorldMatrix(const Matrix4f& WorldInverse)
{
    glUniformMatrix4fv(m_WorldMatrixLocation, 1, GL_TRUE, (const GLfloat*)WorldInverse.m);
}
Exemple #3
0
void LOPuzzle::render()
{
    if (!puzzleTextureID<0 || puzzleObject==0) return;
    
    glEnable(GL_DEPTH_TEST);
    glDisable(GL_BLEND);
    glEnable(GL_CULL_FACE);

    SHTextureBase::bindTexture(puzzleTextureID);
    SunnyMatrix m1 = getScaleMatrix(puzzlePartsScale) *  getRotationXMatrix(M_PI_2);
    SunnyMatrix m;
    puzzleObject->prepareForRender(isVAOSupported);
    
    sunnyUseShader(globalShaders[LOS_Textured3D]);
    glUniform4fv(uniform3D_C, 1, SunnyVector4D(1,1,1,1));

    float depth = 0;
    float shadowD = 0;
    for (short i = puzzleHorizontalSize*puzzleVerticalSize-1;i>=0;i--)
    if (puzzleParts[renderOrder[i]].active)
    {
        if (rotatingParts[renderOrder[i]].isRotating)
        {
            float angle = (- 1 + rotatingParts[renderOrder[i]].time/ppRotationTime)*M_PI_2;
            SunnyVector2D distance = puzzleParts[renderOrder[i]].position - rotatingParts[renderOrder[i]].origin;
            SunnyVector2D pos;
            pos.x = distance.x*cosf(angle) + distance.y*sinf(angle);
            pos.y =-distance.x*sinf(angle) + distance.y*cosf(angle);
            pos += rotatingParts[renderOrder[i]].origin;
            angle = (puzzleParts[renderOrder[i]].rotation - 1 + rotatingParts[renderOrder[i]].time/ppRotationTime)*M_PI_2;
            m = getRotationZMatrix(-angle) * getTranslateMatrix(SunnyVector3D(pos.x,pos.y,-5));
        } else
        {
            m = getRotationZMatrix(-puzzleParts[renderOrder[i]].rotation*M_PI_2) * getTranslateMatrix(SunnyVector3D(puzzleParts[renderOrder[i]].position.x,puzzleParts[renderOrder[i]].position.y,-200+depth));
        }
        if (puzzleHeight[renderOrder[i]]>1)
        {
            m =  getScaleMatrix(puzzleHeight[renderOrder[i]]) * getRotationXMatrix(-M_PI*4*(puzzleHeight[renderOrder[i]]-1))*  m;
            puzzleHeight[renderOrder[i]] -= deltaTime;
            if (puzzleHeight[renderOrder[i]]<1)
                puzzleHeight[renderOrder[i]] = 1;
        }
        m = getTranslateMatrix(partsTranslations[renderOrder[i]]) * m1*m;
        glUniformMatrix4fv(globalModelview[LOS_Textured3D], 1, GL_FALSE, &(m.front.x));
        puzzleObject->renderObject(objectsNumbers[renderOrder[i]]);
        
        if (i+1 == selectedPartsCount)
            shadowD = depth;

        depth += 5;
    }
    
    if (selectedParts)
    {
        glEnable(GL_BLEND);
        SunnyVector3D shadowSize(-0.15,-0.15,-1);
        sunnyUseShader(globalShaders[LOS_Textured3DA]);
        glUniform4fv(uniform3D_A, 1, SunnyVector4D(0,0,0,0.3));
        for (short i = 0;i<selectedPartsCount;i++)
        {
            if (rotatingParts[selectedParts[i]].isRotating)
            {
                float angle = (- 1 + rotatingParts[selectedParts[i]].time/ppRotationTime)*M_PI_2;
                SunnyVector2D distance = puzzleParts[selectedParts[i]].position - rotatingParts[selectedParts[i]].origin;
                SunnyVector2D pos;
                pos.x = distance.x*cosf(angle) + distance.y*sinf(angle);
                pos.y =-distance.x*sinf(angle) + distance.y*cosf(angle);
                pos += rotatingParts[selectedParts[i]].origin;
                angle = (puzzleParts[selectedParts[i]].rotation - 1 + rotatingParts[selectedParts[i]].time/ppRotationTime)*M_PI_2;
                m = getRotationZMatrix(-angle) * getTranslateMatrix(SunnyVector3D(pos.x,pos.y,-5));
            } else
                m = getRotationZMatrix(-puzzleParts[selectedParts[i]].rotation*M_PI_2) * getTranslateMatrix(SunnyVector3D(puzzleParts[selectedParts[i]].position.x+shadowSize.x,puzzleParts[selectedParts[i]].position.y+shadowSize.y,-200+shadowSize.z+shadowD));
            m = getTranslateMatrix(partsTranslations[renderOrder[i]]) * m1*m;
            glUniformMatrix4fv(globalModelview[LOS_Textured3DA], 1, GL_FALSE, &(m.front.x));
            puzzleObject->renderObject(objectsNumbers[selectedParts[i]]);
        }
    }
    glDisable(GL_CULL_FACE);
    glEnable(GL_BLEND);
    glDisable(GL_DEPTH_TEST);
    bindGameGlobal();
    SHTextureBase::bindTexture(menuTexture);
    
    const float mapKoef = mapSize.x/1920;
    const float farDist = -20;
    //fade
    sunnyUseShader(globalShaders[LOS_TexturedTSA]);
    m = sunnyIdentityMatrix;
    glUniformMatrix4fv(globalModelview[LOS_TexturedTSA], 1, GL_FALSE, &(m.front.x));
    glUniform1f(uniformTSA_A, 1);
    
    //Buttons
    {
        
        m = getTranslateMatrix(SunnyVector3D(0,0,farDist));
        glUniform1f(uniformTSA_A, 1);
        float btnScale;
        SunnyMatrix rot;
        rot = m;
        //Back
        rot.pos = puzzleButtons[PuzzleButton_Back]->matrix.pos;
        puzzleButtons[PuzzleButton_Back]->active?btnScale = defaultButtonScale:btnScale = 1;
        glUniformMatrix4fv(globalModelview[LOS_TexturedTSA], 1, GL_FALSE, &(rot.front.x));
        btnScale *= 0.82;
        glUniform4fv(uniformTSA_TR, 1, SunnyVector4D(0, 0, btnScale, btnScale));
        SunnyDrawArrays(LOLCButtonsVAO);
        glUniform4fv(uniformTSA_TR, 1, SunnyVector4D(-4*mapKoef, 6*mapKoef, btnScale, btnScale));
        SunnyDrawArrays(LOLCButtonsVAO+6);
        
//        //Store
//        rot.pos = puzzleButtons[PuzzleButton_Store]->matrix.pos;
//        puzzleButtons[PuzzleButton_Store]->active?btnScale = defaultButtonScale:btnScale = 1;
//        glUniformMatrix4fv(globalModelview[LOS_TexturedTSA], 1, GL_FALSE, &(rot.front.x));
//        glUniform4fv(uniformTSA_TR, 1, SunnyVector4D(0, 0, btnScale, btnScale));
//        SunnyDrawArrays(LOLCButtonsVAO);
//        glUniform4fv(uniformTSA_TR, 1, SunnyVector4D(-4*mapKoef, -2*mapKoef, btnScale, btnScale));
//        SunnyDrawArrays(LOLCButtonsVAO+2);
        
        //break
        if (!puzzleButtons[PuzzleButton_Break]->hidden)
        {
            rot.pos = puzzleButtons[PuzzleButton_Break]->matrix.pos;
            puzzleButtons[PuzzleButton_Break]->active?btnScale = defaultButtonScale:btnScale = 1;
            glUniformMatrix4fv(globalModelview[LOS_TexturedTSA], 1, GL_FALSE, &(rot.front.x));
            btnScale *= 0.82;
            glUniform4fv(uniformTSA_TR, 1, SunnyVector4D(0, 0, btnScale, btnScale));
            SunnyDrawArrays(LOLCButtonsVAO);
            glUniform4fv(uniformTSA_TR, 1, SunnyVector4D(-2*mapKoef, 4*mapKoef, btnScale, btnScale));
            SunnyDrawArrays(LOLCButtonsVAO+3);
        }
    }
}
Exemple #4
0
void LightPassShader::setWVP(const Matrix4& matrix) {
	glUniformMatrix4fv(m_locWVP, 1, true, matrix.m_data);
}
void ShadowMapTechnique::SetWorld(const Matrix4f& World)
{
    glUniformMatrix4fv(m_WorldMatrixLocation, 1, GL_TRUE, (const GLfloat*)World.m);
}
void set_cube_matrix(GLfloat *matrix) {
  glUseProgram(boxShaderProgram);
  glUniformMatrix4fv(boxMatrixLocation, 1, GL_TRUE, matrix);
}
Exemple #7
0
int main () {
	GLFWwindow* window = NULL;
	const GLubyte* renderer;
	const GLubyte* version;
	GLuint vao;
	GLuint vbo;
	GLuint colours_vbo;

	/* geometry to use. these are 3 xyz points (9 floats total) to make a triangle
	*/
	GLfloat points[] = {
		 0.0f,	0.5f,	0.0f,
		 0.5f, -0.5f,	0.0f,
		-0.5f, -0.5f,	0.0f,
		0.00f,	0.8f,	0.0f,
		 -0.5f, -0.2f,	0.0f,
		0.5f, -0.2f,	0.0f

	};

		GLfloat colours[] = {
		1.0f, 1.0f,  0.0f,  //yellow rgb(255,255,0)
		1.0f, 1.0f,  0.0f,
		1.0f, 1.0f,  0.0f,
		1.0f, 0.0f,  0.0f, //red rgb(255,0,0)
		1.0f, 0.0f,  0.0f,
		1.0f, 0.0f,  0.0f,
	};
	/* these are the strings of code for the shaders
	the vertex shader positions each vertex point */
	const char* vertex_shader =
	"#version 400\n"
	"layout(location = 0) in vec3 vertex_position;"
    "layout(location = 1) in vec3 vertex_colour;"
    "out vec3 color;"
	"uniform mat4 matrix;"
	"void main () {"
	"  color = vertex_colour;"
	"	gl_Position=matrix * vec4(vertex_position, 1.0);"
	"}";
	/* the fragment shader colours each fragment (pixel-sized area of the
	triangle) */
	const char* fragment_shader =
	"#version 400\n"
	"in vec3 color;"
	"out vec4 frag_colour;"
	"void main () {"
	"	frag_colour = vec4 (color, 1.0);"
	"}";
	/* GL shader objects for vertex and fragment shader [components] */
	GLuint vs, fs;
	/* GL shader programme object [combined, to link] */
	GLuint shader_programme;

	/* start GL context and O/S window using the GLFW helper library */
	if (!glfwInit ()) {
		fprintf (stderr, "ERROR: could not start GLFW3\n");
		return 1;
	} 

	/* change to 3.2 if on Apple OS X */
	glfwWindowHint (GLFW_CONTEXT_VERSION_MAJOR, 4);
	glfwWindowHint (GLFW_CONTEXT_VERSION_MINOR, 0);
	glfwWindowHint (GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
	glfwWindowHint (GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

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

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

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

	/* a vertex buffer object (VBO) is created here. this stores an array of data
	on the graphics adapter's memory. in our case - the vertex points */
	glGenBuffers (1, &vbo);
	glBindBuffer (GL_ARRAY_BUFFER, vbo);
	glBufferData (GL_ARRAY_BUFFER, 9 * sizeof (GLfloat), points, GL_STATIC_DRAW);
	

	glGenBuffers (1, &colours_vbo);
    glBindBuffer (GL_ARRAY_BUFFER, colours_vbo);
    glBufferData (GL_ARRAY_BUFFER, sizeof (colours), colours, GL_STATIC_DRAW);
	/* the vertex array object (VAO) is a little descriptor that defines which
	data from vertex buffer objects should be used as input variables to vertex
	shaders. in our case - use our only VBO, and say 'every three floats is a 
	variable' */
	glGenVertexArrays (1, &vao);
	glBindVertexArray (vao);
	glEnableVertexAttribArray (0);
	glBindBuffer (GL_ARRAY_BUFFER, vbo);
	glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, 0, NULL);

	glEnableVertexAttribArray (1);  //enable 
	glBindBuffer (GL_ARRAY_BUFFER, colours_vbo);
	glVertexAttribPointer (1, 3, GL_FLOAT, GL_FALSE, 0, NULL);



	
	/* here we copy the shader strings into GL shaders, and compile them. we then
	create an executable shader 'program' and attach both of the compiled shaders.
	we link this, which matches the outputs of the vertex shader to the inputs of
	the fragment shader, etc. and it is then ready to use */
	vs = glCreateShader (GL_VERTEX_SHADER);
	glShaderSource (vs, 1, &vertex_shader, NULL);
	glCompileShader (vs);

	fs = glCreateShader (GL_FRAGMENT_SHADER);
	glShaderSource (fs, 1, &fragment_shader, NULL);
	glCompileShader (fs);
	shader_programme = glCreateProgram ();
	
	glAttachShader (shader_programme, fs);
	glAttachShader (shader_programme, vs);
	glLinkProgram (shader_programme);



double theta=180;

GLfloat matrix[] = {
0.5f,0.0f,0.0f,0.00f,
0.0f,0.5f,0.0f,0.00f,
0.0f,0.0f,0.5f,0.00f,
0.25f,0.5f,0.75f,1.0f,
}; 

int matrix_location = glGetUniformLocation (shader_programme, "matrix");
	

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

		
		glUseProgram (shader_programme);
		glBindVertexArray (vao);

		glDrawArrays (GL_TRIANGLES, 0, 3);
		glDrawArrays (GL_TRIANGLES, 3, 6);
		
		// update other events like input handling 
		glfwPollEvents ();
		if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_ESCAPE)) {
			glfwSetWindowShouldClose (window, 1);
		}

		
		 if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_U)) { //return to normal
		 matrix[0] += 0.015f;
		matrix[5] += 0.005f;
		 }

		 if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_J)) { //return to normal
		 matrix[0] -= 0.015f;
		matrix[5] -= 0.005f;
		 }

		 //uniformed scaling make smaller
		 if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_D)) { //return to normal
		 matrix[0] -= 0.005f;
		 matrix[5] -= 0.005f;
		  }
		
		 //uniformed scaling bigger
		 if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_E)) { //return to normal
		 matrix[0] += 0.005f;
		 matrix[5] += 0.005f;
		 matrix[10] += 0.005f;
		 }

		 //non-uniform scaling
		 if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_X)) { //return to normal
		 
		 matrix[5] = cos(theta);
		 matrix[6] = sin(theta);
		 matrix[9] = -sin(theta);
		 matrix[10] =cos(theta);
		 theta+=0.025;
		}

		//rotation around Y axis
		if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_Y)) { //return to normal
		 matrix[0] = cos(theta);
		 matrix[2] = sin(theta);
		 matrix[8] = -sin(theta);
		 matrix[10] =cos(theta);
		 theta+=0.025;
		}

		//rotation around Z axis
		if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_Z)) { //return to normal
		 matrix[0] = cos(theta);
		 matrix[1] = -sin(theta);
		 matrix[4] = sin(theta);
		 matrix[5] = cos(theta);
		 theta+=0.025;
		}

		//combined transformations
		 if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_C)) {
		 matrix[0] += 0.005f;
		 matrix[5] += 0.005f;
		 matrix[10] +=0.005f;
		 matrix[12] += 0.025f;
		}

		if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_V)) {
		 matrix[0] -= 0.005f;
		 matrix[5] -= 0.005f;
		 matrix[10] -=0.005f;
		 matrix[12] -= 0.025f;
		}

		// X left
		if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_LEFT)) {
				matrix[12] -= 0.025f;
			}

			//X Right
		if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_RIGHT)) {
				matrix[12] += 0.025f;
			}

			//Y Down
		if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_DOWN)) {
				matrix[13] -= 0.025f;
			}


		//Y UP
		if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_UP)) {
				matrix[13] += 0.025f;
			}


		glUniformMatrix4fv (matrix_location, 1, GL_FALSE, matrix); //control triangle seperately
        
		// draw points 0-3 from the currently bound VAO with current in-use shader
		

		// put the stuff we've been drawing onto the display
		glfwSwapBuffers (window);
	}
	
	/* close GL context and any other GLFW resources */
	glfwTerminate();
	return 0;
}
void ShaderProgram::setUniform(int location, const mat4 & m)
{
	glUniformMatrix4fv(location, 1, GL_FALSE, value_ptr(m));
}
Exemple #9
0
	void Shader::SetUniformMat4(uint location, const maths::mat4& matrix)
	{
		glUniformMatrix4fv(location, 1, GL_FALSE, matrix.elements);
	}
Exemple #10
0
void initWaterTest() {
  AQReleasePool *pool = aqinit( aqalloc( &AQReleasePoolType ));
  world = aqinit( aqalloc( &AQWorldType ));
  aqvec2 viewportSize = (aqvec2) { VIEWPORT_WIDTH_HEIGHT };
  AQWorld_setAabb( world, (aqaabb) { viewportSize.y, viewportSize.x, 0, 0 });
  gravity = (aqvec2) { 0, -0.01 / kFrameStep / kFrameStep };
  printf( "gravity %f %f\n", gravity.x, gravity.y );
  AQInput_setWorldFrame( viewportSize.y, viewportSize.x, 0, 0 );
  // aq_input_setscreentoworld((aqbox){ 640, 640, 0, 0 });

  for ( int i = 0; i < particle_count; ++i ) {
    AQParticle *particle = aqcreate( &AQParticleType );
    particle->friction = 0.01;
    particle->correction = 0.5 + (float) rand() / RAND_MAX / 2.5;
    particle->position = (aqvec2) {
      rand() % (int) world->aabb.right,
      rand() % (int) world->aabb.top / 3 * 2
    };
    particle->lastPosition = particle->position;
    particle->radius = kParticleBaseSize + (float) rand() / RAND_MAX * kParticleSizeRange;
    particle->mass = M_PI * particle->radius * particle->radius;
    if ( rand() > RAND_MAX * 0.99 ) {
      // particle->radius += 10;
      particle->mass *= 1000;
    }
    AQWorld_addParticle( world, particle );
  }

  flowLine = aqinit( aqalloc( &AQFlowLineType ));
  flowLine->radius = 20;
  flowLine->minPointDistance = 10;
  flowLine->force = 2.5 / kFrameStep / kFrameStep;
  AQFlowLine_addPoint( flowLine, (aqvec2) { 320, 80 });
  AQFlowLine_addPoint( flowLine, (aqvec2) { 320, 100 });
  AQFlowLine_addPoint( flowLine, (aqvec2) { 320, 120 });
  AQFlowLine_createParticles( flowLine, world );
  AQFlowLine_clearPoints( flowLine );
  printf( "%p %p\n", flowLine->particles, AQList_at( flowLine->particles, 0 ));

  glClearColor(0, 0, 0, 0);
  glEnable(GL_BLEND);
  glBlendFunc(GL_SRC_ALPHA, GL_DST_ALPHA);

  shader_program = glCreateProgram();
  GLuint fragment = glCreateShader(GL_FRAGMENT_SHADER);
  compileShader(fragment, shader_fragment_text);
  glAttachShader(shader_program, fragment);

  GLuint vertex = glCreateShader(GL_VERTEX_SHADER);
  compileShader(vertex, shader_vertex_text);
  glAttachShader(shader_program, vertex);

  glLinkProgram(shader_program);
  GLint programStatus;
  glGetProgramiv(shader_program, GL_LINK_STATUS, &programStatus);
  if (programStatus == GL_FALSE) {
    printf("program failed compilation\n");
  }

  glUseProgram(shader_program);
  positionAttribute = glGetAttribLocation(shader_program, "a_position");
  glEnableVertexAttribArray(positionAttribute);
  colorAttribute = glGetAttribLocation(shader_program, "a_color");
  glEnableVertexAttribArray(colorAttribute);

  GLint modelview_projection = glGetUniformLocation(shader_program, "modelview_projection");
  matrixtAttribute = modelview_projection;
  GLfloat identity[] = {
    1, 0, 0, 0,
    0, 1, 0, 0,
    0, 0, 1, 0,
    0, 0, 0, 1
  };
  glUniformMatrix4fv(modelview_projection, 1, GL_TRUE, identity);

  printf("%d %d %d %d\n", (int) sizeof(AQParticle), shader_program, positionAttribute, modelview_projection);

  glGenBuffers(1, &buffer);

  aqfree( pool );
}
Exemple #11
0
void FShader::ApplyMatrices(VSMatrix *proj, VSMatrix *view)
{
	Bind();
	glUniformMatrix4fv(projectionmatrix_index, 1, false, proj->get());
	glUniformMatrix4fv(viewmatrix_index, 1, false, view->get());
}
Exemple #12
0
void TGLProgram::SetUniformMatrix4x4f(const char* name, const TMatrix4x4f& value)
{
	glUniformMatrix4fv(FindUniform(name), 1, GL_FALSE, value.ToGLmatrix());
}
Exemple #13
0
void SGGLWidget::paintGL() {
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	glColor3f(1, 0, 0);

	QMatrix4x4 camInv;
	camInv.perspective(60.0f, 4.0f / 3.0f, 0.1f, 100.0f);
	camInv.translate(0, 0, -10);

	double points[] =
	{
		0, 1,   -1, -1,   1,-1
	};


	double color[] =
	{
		0, 1, 0,   
		1, 0, 0,
		0, 0, 1
	};

	float matrix[] = {
		1.516395, -1.135207, -0.624707, -0.624695,
		0.000000, 3.027220, -0.468531, -0.468522,
		-1.516395, -1.135207, -0.624707, -0.624695,
		0.000000, -0.000034, 44.622768, 44.821877
	};

	//vertex attribute start//
	GLuint vtxBufferId, uniformId;

	GLuint posLoc = glGetAttribLocation(prid, "position");
	GLuint colorLoc = glGetAttribLocation(prid, "color");
	glEnableVertexAttribArray(posLoc);
	glVertexAttribPointer(posLoc,   2, GL_DOUBLE, GL_FALSE, 0,  points);
	glEnableVertexAttribArray(colorLoc);
	glVertexAttribPointer(colorLoc, 3, GL_DOUBLE, GL_FALSE, 0,  color);

	uniformId = glGetUniformLocation(prid, "matrix");
	glUniformMatrix4fv(uniformId, 1, GL_FALSE, matrix );
	glDrawArrays(GL_TRIANGLES, 0, 3);
	
	
	/*
	glPushMatrix();
	glMultMatrixd(camInv.data());

	glDrawArrays(GL_TRIANGLES, 0, 3);
	glPopMatrix();
	/*
	glPushMatrix();
	glMultMatrixf(dMatrix);
	glBegin(GL_POLYGON);
	glVertex3f(-10.0f, -10.0f, 1.0f);
	glVertex3f(10.0f, -10.0f, 1.0f);
	glVertex3f(10.0f, 10.0f, 1.0f);
	glVertex3f(-10.0f, 10.0f, 1.0f);
	glEnd();

	glBegin(GL_POLYGON);
	glVertex3f(-10.0f, -10.0f, -1.0f);
	glVertex3f(-10.0f, 10.0f, -1.0f);
	glVertex3f(10.0f, 10.0f, -1.0f);
	glVertex3f(10.0f, -10.0f, -1.0f);
	glEnd();
	
	glPopMatrix();/**/
	
	sgPrintf("paint");
}
Exemple #14
0
void CGEDebugger::UpdatePrimPreview(u32 op) {
	const u32 prim_type = (op >> 16) & 0xFF;
	int count = op & 0xFFFF;
	if (prim_type >= 7) {
		ERROR_LOG(COMMON, "Unsupported prim type: %x", op);
		return;
	}
	if (!gpuDebug) {
		ERROR_LOG(COMMON, "Invalid debugging environment, shutting down?");
		return;
	}
	if (count == 0) {
		return;
	}

	const GEPrimitiveType prim = static_cast<GEPrimitiveType>(prim_type);
	static std::vector<GPUDebugVertex> vertices;
	static std::vector<u16> indices;

	if (!gpuDebug->GetCurrentSimpleVertices(count, vertices, indices)) {
		ERROR_LOG(COMMON, "Vertex preview not yet supported");
		return;
	}

	if (prim == GE_PRIM_RECTANGLES) {
		ExpandRectangles(vertices, indices, count, gpuDebug->GetGState().isModeThrough());
	}

	float fw, fh;
	float x, y;

	frameWindow->Begin();
	frameWindow->GetContentSize(x, y, fw, fh);

	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glBlendEquation(GL_FUNC_ADD);
	glBindTexture(GL_TEXTURE_2D, 0);
	glViewport((GLint)x, (GLint)y, (GLsizei)fw, (GLsizei)fh);
	glScissor((GLint)x, (GLint)y, (GLsizei)fw, (GLsizei)fh);
	BindPreviewProgram(previewProgram);

	float scale[] = {
		480.0f / (float)PSP_CoreParameter().renderWidth,
		272.0f / (float)PSP_CoreParameter().renderHeight,
	};

	Matrix4x4 ortho;
	ortho.setOrtho(0, frameWindow->TexWidth() * scale[0], frameWindow->TexHeight() * scale[1], 0, -1, 1);
	glUniformMatrix4fv(previewProgram->u_viewproj, 1, GL_FALSE, ortho.getReadPtr());
	glEnableVertexAttribArray(previewProgram->a_position);
	glVertexAttribPointer(previewProgram->a_position, 3, GL_FLOAT, GL_FALSE, sizeof(GPUDebugVertex), (float *)vertices.data() + 2);

	if (indices.empty()) {
		glDrawArrays(glprim[prim], 0, count);
	} else {
		glDrawElements(glprim[prim], count, GL_UNSIGNED_SHORT, indices.data());
	}

	frameWindow->End();

	texWindow->Begin();
	texWindow->GetContentSize(x, y, fw, fh);

	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glBlendEquation(GL_FUNC_ADD);
	glBindTexture(GL_TEXTURE_2D, 0);
	glViewport((GLint)x, (GLint)y, (GLsizei)fw, (GLsizei)fh);
	glScissor((GLint)x, (GLint)y, (GLsizei)fw, (GLsizei)fh);
	BindPreviewProgram(texPreviewProgram);

	// TODO: Probably there's a better way and place to do this.
	if (indices.empty()) {
		for (int i = 0; i < count; ++i) {
			vertices[i].u -= floor(vertices[i].u);
			vertices[i].v -= floor(vertices[i].v);
		}
	} else {
		for (int i = 0; i < count; ++i) {
			vertices[indices[i]].u -= floor(vertices[indices[i]].u);
			vertices[indices[i]].v -= floor(vertices[indices[i]].v);
		}
	}

	ortho.setOrtho(0.0, 1.0, 1.0, 0.0, -1.0, 1.0);
	glUniformMatrix4fv(texPreviewProgram->u_viewproj, 1, GL_FALSE, ortho.getReadPtr());
	glEnableVertexAttribArray(texPreviewProgram->a_position);
	glVertexAttribPointer(texPreviewProgram->a_position, 2, GL_FLOAT, GL_FALSE, sizeof(GPUDebugVertex), (float *)vertices.data());
	if (indices.empty()) {
		glDrawArrays(glprim[prim], 0, count);
	} else {
		glDrawElements(glprim[prim], count, GL_UNSIGNED_SHORT, indices.data());
	}

	texWindow->End();
}
Exemple #15
0
void Shader::SetUniform( Int32 loc, const glm::mat4 *mat, UInt32 size) {
    glUniformMatrix4fv(loc, size, GL_FALSE, (GLfloat*)mat);
}
Exemple #16
0
int main(void)
{
    glfwSetErrorCallback(error_callback);

    if (!glfwInit())
        exit(EXIT_FAILURE);

    GLFWmonitor *monitor = glfwGetPrimaryMonitor();
    const GLFWvidmode *mode = glfwGetVideoMode(monitor);
    printf("monitor mode: %d, %d\n", mode->width, mode->height);

    // if DEBUG {
    //     glfw.WindowHint(glfw.OpenGLDebugContext, gl.TRUE)
    // }

    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, 1);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    GLFWwindow *window = glfwCreateWindow(mode->width, mode->height, "Hialin", NULL, NULL);
    if (!window) {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    glfwSetKeyCallback(window, key_callback);

    glfwMakeContextCurrent(window);
    glfwSwapInterval(0);

    p_glBindFragDataLocation = (glBindFragDataLocation_t)glfwGetProcAddress("glBindFragDataLocation");
    if (!p_glBindFragDataLocation) {
        printf("\n failed glBindFragDataLocation");
        glfwTerminate();
        exit(EXIT_FAILURE);
    }
    p_glGenVertexArrays = (glGenVertexArrays_t)glfwGetProcAddress("glGenVertexArrays");
    if (!p_glGenVertexArrays) {
        printf("\n failed glGenVertexArrays");
        glfwTerminate();
        exit(EXIT_FAILURE);
    }
    p_glBindVertexArray = (glBindVertexArray_t)glfwGetProcAddress("glBindVertexArray");
    if (!p_glBindVertexArray) {
        printf("\n failed glBindVertexArray");
        glfwTerminate();
        exit(EXIT_FAILURE);
    }


    GLuint vsh = glCreateShader(GL_VERTEX_SHADER);
    {
        glShaderSource(vsh, 1, &vertex_shader_text, NULL);
        glCompileShader(vsh);
        int result;
        glGetShaderiv(vsh, GL_COMPILE_STATUS, &result );
        if (result == GL_FALSE) {
            int logLength;
            glGetShaderiv(vsh, GL_INFO_LOG_LENGTH, &logLength);
            char log[10*1024] = {0};
            glGetShaderInfoLog(vsh, logLength, NULL, log);
            printf("\nvertex shader compile: %s", log);
            glfwTerminate();
            exit(EXIT_FAILURE);
        }
    }
    glCheck();

    GLuint fsh = glCreateShader(GL_FRAGMENT_SHADER);
    {
        glShaderSource(fsh, 1, &fragment_shader_text, NULL);
        glCompileShader(fsh);
        int result;
        glGetShaderiv(fsh, GL_COMPILE_STATUS, &result);
        if (result == GL_FALSE) {
            int logLength;
            glGetShaderiv(fsh, GL_INFO_LOG_LENGTH, &logLength);
            char log[10*1024] = {0};
            glGetShaderInfoLog(fsh, logLength, NULL, log);
            printf("\nfragment shader compile: %s", log);
            glfwTerminate();
            exit(EXIT_FAILURE);
        }
    }
    glCheck();

    GLuint program = glCreateProgram();
    {
        glAttachShader(program, vsh);
        glAttachShader(program, fsh);
        glLinkProgram(program);
        int result;
        glGetProgramiv(program, GL_LINK_STATUS, &result);
        if (result == GL_FALSE) {
            int logLength;
            glGetProgramiv(program, GL_INFO_LOG_LENGTH, &logLength);
            char log[10*1024] = {0};
            glGetProgramInfoLog(program, logLength, NULL, log);
            printf("\nprogram link: \n%s", log);
            glfwTerminate();
            exit(EXIT_FAILURE);
        }
    }
    glCheck();
    glUseProgram(program);
    glCheck();

    GLint projectionU = glGetUniformLocation(program, "projection");

    mat4x4 camera;
    vec3 eye = {3, 3, 3}, center = {0, 0, 0}, up = {0, 1, 0};
    mat4x4_look_at(camera, eye, center, up);
    GLint cameraU = glGetUniformLocation(program, "camera");
    glUniformMatrix4fv(cameraU, 1, GL_FALSE, (const float*)camera);
    glCheck();

    mat4x4 model;
    mat4x4_identity(model);
    GLint modelU = glGetUniformLocation(program, "model");
    glUniformMatrix4fv(modelU, 1, GL_FALSE, (const float*)model);
    glCheck();

    GLint texU = glGetUniformLocation(program, "tex");
    glUniform1i(texU, 0);
    p_glBindFragDataLocation(program, 0, "outputColor");
    glCheck();

    // Load the texture
    // char *texturePath = "./Resources/code.png"
    // GLuint texture = MakeTexture(0, texturePath);
    GLuint texture = MakeTexture(0);
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, texture);
    glCheck();

    // Configure the vertex data
    GLuint vao;
    p_glGenVertexArrays(1, &vao);
    p_glBindVertexArray(vao);
    glCheck();

    GLuint vbo;
    glGenBuffers(1, &vbo);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(cube_vertices), cube_vertices, GL_STATIC_DRAW);
    glCheck();

    GLuint val = glGetAttribLocation(program, "vert");
    glEnableVertexAttribArray(val);
    glVertexAttribPointer(val, 3, GL_FLOAT, GL_FALSE, 5*4, (const void *)(0*4));
    glCheck();

    GLuint valTC = glGetAttribLocation(program, "vertTexCoord");
    glEnableVertexAttribArray(valTC);
    glVertexAttribPointer(valTC, 2, GL_FLOAT, GL_FALSE, 5*4, (const void *)(3*4));
    glCheck();

    // Configure global settings
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LESS);
    glClearColor(0.0, 0.0, 0.0, 1.0);
    glCheck();

    long time0 = tick();

    float angle = 0.01;

    int width = 0, height = 0;
    int i = 0;
    while (!glfwWindowShouldClose(window))
    {
        int w, h;
        glfwGetFramebufferSize(window, &w, &h);
        if (w != width || h != height) {
            width = w;
            height = h;
            glViewport(0, 0, width, height);
            printf("buffer size: %d %d\n", w, h);
        }
        float ratio = width/(float)height;

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        mat4x4_rotate_Y(model, model, angle);

        mat4x4 projection;
        mat4x4_perspective(projection, 0.785, ratio, 0.1, 10.0); // 45 degrees == 0.785 radians

        glUniformMatrix4fv(projectionU, 1, GL_FALSE, (const float*)projection);
        glUniformMatrix4fv(modelU, 1, GL_FALSE, (const float*)model);

        for (int i = 0; i < 1*1000; i++) {
            glDrawArrays(GL_TRIANGLES, 0, 6*2*3); // 12 triangles
        }

        i++;
        if (i == 100) {
            printf("time for 100 frames: %ld\n", tick()-time0);
        } else if (i == 1000) {
            printf("time for 1000 frames: %ld\n", tick()-time0);
            break;
        }

        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    glfwDestroyWindow(window);

    glfwTerminate();
    exit(EXIT_SUCCESS);
}
Exemple #17
0
void Shader::SetUniform(Int32 loc, const glm::mat4 &mat) {
    glUniformMatrix4fv(loc, 1, GL_FALSE, glm::value_ptr(mat));
}
void
TriangleApplication::OnDraw() const
{
    // Clear the color buffer with black.
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);

    // Send the PMV matrix - in this case, an identity matrix -
    // to the Program.
    glUniformMatrix4fv(
        // Get the "slot" number in the Program
        // where `u_PMV_matrix` should be located.
        program->GetUniformLocation("u_PMV_matrix"),
        // We will only send 1 matrix data
        1,
        // The matrix data not need to be transposed.
        // Furthermore, The OpenGL ES 2 spec also says
        // this must be `GL_FALSE`. Weird, huh?
        GL_FALSE,
        // The matrix data itself.
        kIdentityMatrix);

    // Activate the vertex position attribute.
    glEnableVertexAttribArray(kVertexPosition);

    // Send the vertex position data to Program.
    glVertexAttribPointer(
        // The index of attrib.
        kVertexPosition,
        // The component size. In this case is 3
        // (x, y, and z) for position attrib.
        3,
        // The type of the position attrib data.
        // In this case, we use float for position
        // data.
        GL_FLOAT,
        // This data needn't to be normalized.
        GL_FALSE,
        // The stride of the data. In this case,
        // the data is continuous, so no stride.
        // No stride equals 0.
        0,
        // The data itself.
        kVerticesPosition);

    // Now that:
    // 1. The minimalist GPU program have been built and activated
    //    in the GPU, and
    // 2. The position for 3 vertices that will formed a triangle
    //    has been uploaded to the GPU,
    // we can draw the triangle.
    glDrawArrays(
        // Tell OpenGL that we're going to draw triangle primitive.
        // Other option for primitive includes points (`GL_POINTS`) and
        // lines (`GL_LINES`).
        GL_TRIANGLES,
        // Start the drawing from 0th element of the enabled vertex
        // attribute array(s). In this case, the only enabled vertex
        // attribute array is the vertex position.
        0,
        // Tell OpenGL to draw 3 vertices. Triangle needs 3 vertices,
        // remember?
        3);
}
Exemple #19
0
void ShaderProgram::setUniformMatrix4fv(u32 location, u32 count, boolean normalize, f32* value)
{
    glUniformMatrix4fv(location, count, normalize, value);
}
Exemple #20
0
void program_draw( void *ptr )
{
	unsigned int i = 0;
	
	PROGRAM *program = ( PROGRAM * )ptr;
	
	while( i != program->uniform_count )
	{
		if( program->uniform_array[ i ].constant ) 
		{
			++i;
			continue;
		}
	
		else if( !strcmp( program->uniform_array[ i ].name, "MODELVIEWPROJECTIONMATRIX" ) )
		{
			glUniformMatrix4fv( program->uniform_array[ i ].location,
								1,
								GL_FALSE,
								( float * )GFX_get_modelview_projection_matrix() );			
		}
		
		else if( !strcmp( program->uniform_array[ i ].name, "PROJECTOR" ) )
		{
			glUniform1i( program->uniform_array[ i ].location,
						 0 );

			program->uniform_array[ i ].constant = 1;
		}		
		
		else if( !strcmp( program->uniform_array[ i ].name, "DIFFUSE" ) )
		{
			glUniform1i( program->uniform_array[ i ].location,
						 1 );

			program->uniform_array[ i ].constant = 1;
		}

		else if( !strcmp( program->uniform_array[ i ].name, "BUMP" ) )
		{
			glUniform1i( program->uniform_array[ i ].location,
						 4 );
						 
			program->uniform_array[ i ].constant = 1;
		}
		

		// Matrix Data
		else if( !strcmp( program->uniform_array[ i ].name, "MODELVIEWMATRIX" ) )
		{
			glUniformMatrix4fv( program->uniform_array[ i ].location,
								1,
								GL_FALSE,
								( float * )GFX_get_modelview_matrix() );			
		}

		else if( !strcmp( program->uniform_array[ i ].name, "PROJECTIONMATRIX" ) )
		{
			glUniformMatrix4fv( program->uniform_array[ i ].location,
								1,
								GL_FALSE,
								( float * )GFX_get_projection_matrix() );
			
			program->uniform_array[ i ].constant = 1;
		}

		else if( !strcmp( program->uniform_array[ i ].name, "NORMALMATRIX" ) )
		{
			glUniformMatrix3fv( program->uniform_array[ i ].location,
								1,
								GL_FALSE,
								( float * )GFX_get_normal_matrix() );			
		}
		
		else if( !strcmp( program->uniform_array[ i ].name, "PROJECTORMATRIX" ) )
		{
			glUniformMatrix4fv( program->uniform_array[ i ].location,
								1,
								GL_FALSE,
								( float * )&projector_matrix );			
		}		
		

		// Material Data
		else if( !strcmp( program->uniform_array[ i ].name, "MATERIAL.ambient" ) )
		{
			glUniform4fv( program->uniform_array[ i ].location,
						  1,
						  ( float * )&objmesh->current_material->ambient );
						 
			program->uniform_array[ i ].constant = 1;
		}		

		else if( !strcmp( program->uniform_array[ i ].name, "MATERIAL.diffuse" ) )
		{
			glUniform4fv( program->uniform_array[ i ].location,
						  1,
						  ( float * )&objmesh->current_material->diffuse );

			program->uniform_array[ i ].constant = 1;
		}		

		else if( !strcmp( program->uniform_array[ i ].name, "MATERIAL.specular" ) )
		{
			glUniform4fv( program->uniform_array[ i ].location,
						  1,
						  ( float * )&objmesh->current_material->specular );

			program->uniform_array[ i ].constant = 1;
		}		

		else if( !strcmp( program->uniform_array[ i ].name, "MATERIAL.shininess" ) )
		{
			glUniform1f( program->uniform_array[ i ].location,
						 objmesh->current_material->specular_exponent * 0.128f );

			program->uniform_array[ i ].constant = 1;
		}
		
		
		// Light Data
		else if( !strcmp( program->uniform_array[ i ].name, "LIGHT_FS.color" ) )
		{
			glUniform4fv( program->uniform_array[ i ].location,
						  1,
						  ( float * )&light->color );

			program->uniform_array[ i ].constant = 1;
		}

		else if( !strcmp( program->uniform_array[ i ].name, "LIGHT_VS.position" ) )
		{
			vec4 position;

			static float rot_angle = 0.0f;
		
			light->position.x = 7.5f * cosf( rot_angle * DEG_TO_RAD );
			light->position.y = 7.5f * sinf( rot_angle * DEG_TO_RAD );
		
			rot_angle += 0.25f;
					
			LIGHT_get_position_in_eye_space( light,
											 &gfx.modelview_matrix[ gfx.modelview_matrix_index - 1 ], 
											 &position );

			glUniform3fv( program->uniform_array[ i ].location,
						  1,
						  ( float * )&position );
		}
		
		else if( !strcmp( program->uniform_array[ i ].name, "LIGHT_VS.spot_direction" ) )
		{
			vec3 direction;
			
			vec3_diff( &light->spot_direction, &center, ( vec3 * )&light->position );
		
			vec3_normalize( &light->spot_direction,
							&light->spot_direction );

			LIGHT_get_direction_in_object_space( light,
												 &gfx.modelview_matrix[ gfx.modelview_matrix_index - 1 ],
												 &direction );

			glUniform3fv( program->uniform_array[ i ].location,
						  1,
						  ( float * )&direction );
		}
		
		else if( !strcmp( program->uniform_array[ i ].name, "LIGHT_FS.spot_cos_cutoff" ) )
		{
			glUniform1f( program->uniform_array[ i ].location,
						 light->spot_cos_cutoff );

			program->uniform_array[ i ].constant = 1;
		}


		else if( !strcmp( program->uniform_array[ i ].name, "LIGHT_FS.spot_blend" ) )
		{
			glUniform1f( program->uniform_array[ i ].location,
						 light->spot_blend );

			program->uniform_array[ i ].constant = 1;
		}		
		
		++i;
	}
}
Exemple #21
0
void SSAO::runShader(MeshDocument& md, GLArea* gla){

        /***********************************************************/
        //NORMAL MAP and DEPTH MAP generation
        /***********************************************************/
        this->bind();
        glUseProgram(this->_normalMapShaderProgram);
        RenderMode rm = gla->getCurrentRenderMode();

        vcg::Matrix44f mProj, mInverseProj;
        glMatrixMode(GL_PROJECTION);
        glGetFloatv(GL_PROJECTION_MATRIX, mProj.V());
        glMatrixMode(GL_MODELVIEW);

        mProj.transposeInPlace();
        mInverseProj = vcg::Inverse(mProj);

        glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        foreach(MeshModel *m, md.meshList)
        if(m->visible)
          {
            m->render(vcg::GLW::DMFlat, vcg::GLW::CMNone, vcg::GLW::TMNone);
          }
        glUseProgram(0);

        /***********************************************************/
        //SSAO PASS
        /***********************************************************/
        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, _fbo2);
        glUseProgram(this->_ssaoShaderProgram);

        glEnable(GL_TEXTURE_2D);
        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, this->_noise);
        GLuint noiseloc = glGetUniformLocation(this->_ssaoShaderProgram, "rnm");
        glUniform1i(noiseloc, 0);

        glActiveTexture(GL_TEXTURE1);
        glBindTexture(GL_TEXTURE_2D, this->_color1);
        GLuint loc = glGetUniformLocation(this->_ssaoShaderProgram, "normalMap");
        glUniform1i(loc, 1);


        glActiveTexture(GL_TEXTURE2);
        glBindTexture(GL_TEXTURE_2D, this->_depthMap);
        loc = glGetUniformLocation(this->_ssaoShaderProgram, "depthMap");
        glUniform1i(loc, 2);

        GLuint radiusLoc = glGetUniformLocation(this->_ssaoShaderProgram, "rad");
        glUniform1f(radiusLoc, this->_radius);

        GLuint matrixLoc = glGetUniformLocation(this->_ssaoShaderProgram, "proj");
        glUniformMatrix4fv(matrixLoc, 1, 0, mProj.transpose().V());

        GLuint invMatrixLoc = glGetUniformLocation(this->_ssaoShaderProgram, "invProj");
        glUniformMatrix4fv(invMatrixLoc, 1, 0, mInverseProj.transpose().V());

        glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
            glBegin(GL_TRIANGLE_STRIP);
                glVertex3f(-1.0f, -1.0f, 0.0f);
                glVertex3f( 1.0f, -1.0f, 0.0f);
                glVertex3f(-1.0f,  1.0f, 0.0f);
                glVertex3f( 1.0f,  1.0f, 0.0f);
            glEnd();
        glUseProgram(0);

        /***********************************************************/
        //BLURRING horizontal
        /***********************************************************/
        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, _fbo);
        glUseProgram(this->_blurShaderProgram);

        float blur_coef = 0.8;
        GLfloat scale = 1/(this->_texW * blur_coef);

        GLuint scaleLoc = glGetUniformLocation(this->_blurShaderProgram, "scale");
        glUniform2f(scaleLoc, scale, 0.0);

        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, this->_color2);
        loc = glGetUniformLocation(this->_blurShaderProgram, "scene");
        glUniform1i(loc, 0);

        glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
            glBegin(GL_TRIANGLE_STRIP);
                glVertex3f(-1.0f, -1.0f, 0.0f);
                glVertex3f( 1.0f, -1.0f, 0.0f);
                glVertex3f(-1.0f,  1.0f, 0.0f);
                glVertex3f( 1.0f,  1.0f, 0.0f);
            glEnd();

        /***********************************************************/
        //BLURRING vertical
        /***********************************************************/
        this->unbind();
        glUniform2f(scaleLoc, 0.0, scale);
        glDisable(GL_DEPTH_TEST);
        glEnable(GL_BLEND);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
        glBindTexture(GL_TEXTURE_2D, this->_color1);
        loc = glGetUniformLocation(this->_blurShaderProgram, "scene");
        glUniform1i(loc, 0);

            glBegin(GL_TRIANGLE_STRIP);
                glVertex3f(-1.0f, -1.0f, 0.0f);
                glVertex3f( 1.0f, -1.0f, 0.0f);
                glVertex3f(-1.0f,  1.0f, 0.0f);
                glVertex3f( 1.0f,  1.0f, 0.0f);
            glEnd();

        glUseProgram(0);
        glEnable(GL_DEPTH_TEST);
        glDisable(GL_TEXTURE_2D);
        glDisable(GL_BLEND);
}
int main()
{
    // glfw: initialize and configure
    // ------------------------------
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    //glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // uncomment this statement to fix compilation on OS X

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

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

    // build and compile our shader zprogram
    // ------------------------------------
    Shader ourShader("5.2.transform.vs", "5.2.transform.fs");

    // set up vertex data (and buffer(s)) and configure vertex attributes
    // ------------------------------------------------------------------
    float vertices[] = {
        // positions           // texture coords
         0.5f,  0.5f, 0.0f,    1.0f, 1.0f, // top right
         0.5f, -0.5f, 0.0f,    1.0f, 0.0f, // bottom right
        -0.5f, -0.5f, 0.0f,    0.0f, 0.0f, // bottom left
        -0.5f,  0.5f, 0.0f,    0.0f, 1.0f  // top left 
    };
    unsigned int indices[] = {
        0, 1, 3, // first triangle
        1, 2, 3  // second triangle
    };
    unsigned int VBO, VAO, EBO;
    glGenVertexArrays(1, &VAO);
    glGenBuffers(1, &VBO);
    glGenBuffers(1, &EBO);

    glBindVertexArray(VAO);

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

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

    // position attribute
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0);
    glEnableVertexAttribArray(0);
    // texture coord attribute
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float)));
    glEnableVertexAttribArray(1);


    // load and create a texture 
    // -------------------------
    unsigned int texture1, texture2;
    // texture 1
    // ---------
    glGenTextures(1, &texture1);
    glBindTexture(GL_TEXTURE_2D, texture1);
    // set the texture wrapping parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    // set texture filtering parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    // load image, create texture and generate mipmaps
    int width, height, nrChannels;
    stbi_set_flip_vertically_on_load(true); // tell stb_image.h to flip loaded texture's on the y-axis.
    unsigned char *data = stbi_load(FileSystem::getPath("resources/textures/container.jpg").c_str(), &width, &height, &nrChannels, 0);
    if (data)
    {
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
        glGenerateMipmap(GL_TEXTURE_2D);
    }
    else
    {
        std::cout << "Failed to load texture" << std::endl;
    }
    stbi_image_free(data);
    // texture 2
    // ---------
    glGenTextures(1, &texture2);
    glBindTexture(GL_TEXTURE_2D, texture2);
    // set the texture wrapping parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);	
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    // set texture filtering parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    // load image, create texture and generate mipmaps
    data = stbi_load(FileSystem::getPath("resources/textures/awesomeface.png").c_str(), &width, &height, &nrChannels, 0);
    if (data)
    {
        // note that the awesomeface.png has transparency and thus an alpha channel, so make sure to tell OpenGL the data type is of GL_RGBA
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
        glGenerateMipmap(GL_TEXTURE_2D);
    }
    else
    {
        std::cout << "Failed to load texture" << std::endl;
    }
    stbi_image_free(data);

    // tell opengl for each sampler to which texture unit it belongs to (only has to be done once)
    // -------------------------------------------------------------------------------------------
    ourShader.use();
    ourShader.setInt("texture1", 0);
    ourShader.setInt("texture2", 1);


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

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

        // bind textures on corresponding texture units
        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, texture1);
        glActiveTexture(GL_TEXTURE1);
        glBindTexture(GL_TEXTURE_2D, texture2);


        glm::mat4 transform;
        // first container
        // ---------------
        transform = glm::translate(transform, glm::vec3(0.5f, -0.5f, 0.0f));
        transform = glm::rotate(transform, (float)glfwGetTime(), glm::vec3(0.0f, 0.0f, 1.0f));
        // get their uniform location and set matrix (using glm::value_ptr)
        unsigned int transformLoc = glGetUniformLocation(ourShader.ID, "transform");
        glUniformMatrix4fv(transformLoc, 1, GL_FALSE, glm::value_ptr(transform));

        // with the uniform matrix set, draw the first container
        glBindVertexArray(VAO);
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);

        // second transformation
        // ---------------------
        transform = glm::mat4(); // reset it to an identity matrix
        transform = glm::translate(transform, glm::vec3(-0.5f, 0.5f, 0.0f));
        float scaleAmount = sin(glfwGetTime());
        transform = glm::scale(transform, glm::vec3(scaleAmount, scaleAmount, scaleAmount));
        glUniformMatrix4fv(transformLoc, 1, GL_FALSE, &transform[0][0]); // this time take the matrix value array's first element as its memory pointer value

        // now with the uniform matrix being replaced with new transformations, draw it again.
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);

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

    // optional: de-allocate all resources once they've outlived their purpose:
    // ------------------------------------------------------------------------
    glDeleteVertexArrays(1, &VAO);
    glDeleteBuffers(1, &VBO);
    glDeleteBuffers(1, &EBO);

    // glfw: terminate, clearing all previously allocated GLFW resources.
    // ------------------------------------------------------------------
    glfwTerminate();
    return 0;
}
void ShadowMapTechnique::SetWVP(const Matrix4f& WVP)
{
    glUniformMatrix4fv(m_WVPLocation, 1, GL_TRUE, (const GLfloat*)WVP.m);
}
Exemple #24
0
GLUSboolean update(GLUSfloat time)
{
	GLfloat modelMatrix[16];
	GLfloat normalMatrix[9];

	//
	// Render to FBO.
	//

	glActiveTexture(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_CUBE_MAP_ARRAY, g_texture[0]);

	glActiveTexture(GL_TEXTURE1);
	glBindTexture(GL_TEXTURE_CUBE_MAP, g_texture[1]);

	glActiveTexture(GL_TEXTURE2);
	glBindTexture(GL_TEXTURE_2D, g_texture[2]);

	glActiveTexture(GL_TEXTURE0);

	glBindFramebuffer(GL_FRAMEBUFFER, g_fullscreenFBO);

	glEnable(GL_MULTISAMPLE);

	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	// Render the background.

	// Rendering the sphere from inside, so change front facing.
	glFrontFace(GL_CW);

	glUseProgram(g_backgroundProgram.program);

	glUniformMatrix4fv(g_viewProjectionMatrixBackgroundLocation, 1, GL_FALSE, g_viewProjectionMatrix);

	glBindVertexArray(g_backgroundVAO);

	glDrawElements(GL_TRIANGLES, g_numberIndicesBackground, GL_UNSIGNED_INT, 0);

	glFrontFace(GL_CCW);

	// Render model using BRDF and IBL.

	glusMatrix4x4Identityf(modelMatrix);
	glusMatrix4x4Scalef(modelMatrix, 0.001f, 0.001f, 0.001f);

	glusMatrix4x4ExtractMatrix3x3f(normalMatrix, modelMatrix);

	glUseProgram(g_modelProgram.program);

	glBindVertexArray(g_modelVAO);

	// Roughness of material.
	glUniform1f(g_roughnessMaterialModelLocation, g_roughness);
	glUniform1f(g_R0MaterialModelLocation, g_R0);
	glUniform3fv(g_colorMaterialModelLocation, 1, g_colorMaterial);

	glUniformMatrix4fv(g_viewProjectionMatrixModelLocation, 1, GL_FALSE, g_viewProjectionMatrix);
	glUniformMatrix4fv(g_modelMatrixModelLocation, 1, GL_FALSE, modelMatrix);
	glUniformMatrix3fv(g_normalMatrixModelLocation, 1, GL_FALSE, normalMatrix);

	glDrawArrays(GL_TRIANGLES, 0, g_numberVerticesModel);

	//
	// Render full screen to resolve the buffer: MSAA, tone mapping and gamma correction.
	//

	glActiveTexture(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, g_fullscreenTexture);

	glBindFramebuffer(GL_FRAMEBUFFER, 0);

	glDisable(GL_MULTISAMPLE);

	// No clear needed, as we just draw over the last content.
	glDisable(GL_DEPTH_TEST);

	glUseProgram(g_fullscreenProgram.program);

	glUniform1f(g_exposureFullscreenLocation, g_exposure);
	glUniform1f(g_gammaFullscreenLocation, g_gamma);

	glBindVertexArray(g_fullscreenVAO);

	glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

	glEnable(GL_DEPTH_TEST);

	return GLUS_TRUE;
}
void LightingTechnique::SetLightWVP(const Matrix4f& LightWVP)
{
    glUniformMatrix4fv(m_LightWVPLocation, 1, GL_TRUE, (const GLfloat*)LightWVP.m);
}
Exemple #26
0
static void
render_unlocked(glw_root_t *gr)
{
  glw_backend_root_t *gbr = &gr->gr_be;
  render_state_t rs = {0};

  int64_t ts = arch_get_ts();

  int current_blendmode = GLW_BLEND_NORMAL;
  glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA,
		      GL_ONE_MINUS_DST_ALPHA, GL_ONE);

  const float *vertices = gr->gr_vertex_buffer;

  glBindBuffer(GL_ARRAY_BUFFER, gbr->gbr_vbo);
  glBufferData(GL_ARRAY_BUFFER,
	       sizeof(float) * VERTEX_SIZE * gr->gr_vertex_offset,
	       vertices, GL_STATIC_DRAW);

  int current_frontface = GLW_CCW;
  glFrontFace(GL_CCW);

  vertices = NULL;
  glVertexAttribPointer(0, 4, GL_FLOAT, 0, sizeof(float) * VERTEX_SIZE,
			vertices);

  glVertexAttribPointer(1, 4, GL_FLOAT, 0, sizeof(float) * VERTEX_SIZE,
			vertices + 4);

  glVertexAttribPointer(2, 4, GL_FLOAT, 0, sizeof(float) * VERTEX_SIZE,
			vertices + 8);

  for(int j = 0; j < gr->gr_num_render_jobs; j++) {
    const glw_render_order_t *ro = gr->gr_render_order + j;
    const glw_render_job_t *rj = ro->job;

    if(unlikely(rj->num_vertices == 0))
      continue;

    const struct glw_backend_texture *t0 = rj->t0;

    glw_program_t *gp =
      load_program(gr, t0, rj->t1, rj->blur, rj->flags, rj->gpa, &rs, rj);

    if(gbr->gbr_use_stencil_buffer)
      glStencilFunc(GL_GEQUAL, ro->zindex, 0xFF);

    if(unlikely(gp == NULL)) {

#if ENABLE_GLW_BACKEND_OPENGL
      if(rj->eyespace) {
        glLoadMatrixf(glw_identitymtx);
      } else {
        glLoadMatrixf(glw_mtx_get(rj->m));
      }

      glBegin(GL_QUADS);
      if(t0 != NULL)
        glTexCoord2i(0, t0->height);
      glVertex3i(-1, -1, 0);

      if(t0 != NULL)
        glTexCoord2i(t0->width, t0->height);
      glVertex3i(1, -1, 0);

      if(t0 != NULL)
        glTexCoord2i(t0->width, 0);
      glVertex3i(1, 1, 0);

      if(t0 != NULL)
        glTexCoord2i(0, 0);
      glVertex3i(-1, 1, 0);

      glEnd();

      glDisable(t0->gltype);
#endif
      continue;

    } else {

      glUniform4f(gp->gp_uniform_color_offset,
                  rj->rgb_off.r, rj->rgb_off.g, rj->rgb_off.b, 0);

      glUniform4f(gbr->gbr_current->gp_uniform_color,
                  rj->rgb_mul.r, rj->rgb_mul.g, rj->rgb_mul.b, rj->alpha);

      if(gp->gp_uniform_time != -1)
        glUniform1f(gp->gp_uniform_time, gr->gr_time_sec);

      if(gp->gp_uniform_resolution != -1)
        glUniform3f(gp->gp_uniform_resolution, rj->width, rj->height, 1);

      if(gp->gp_uniform_blur != -1 && t0 != NULL)
        glUniform3f(gp->gp_uniform_blur, rj->blur,
                    1.5 / t0->width, 1.5 / t0->height);

      if(rj->eyespace) {
        glUniformMatrix4fv(gp->gp_uniform_modelview, 1, 0, glw_identitymtx);
      } else {
        glUniformMatrix4fv(gp->gp_uniform_modelview, 1, 0, glw_mtx_get(rj->m));
      }
    }
    if(unlikely(current_blendmode != rj->blendmode)) {
      current_blendmode = rj->blendmode;
      switch(current_blendmode) {
      case GLW_BLEND_NORMAL:
	glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA,
			    GL_ONE_MINUS_DST_ALPHA, GL_ONE);

	break;

      case GLW_BLEND_ADDITIVE:
	glBlendFuncSeparate(GL_SRC_COLOR, GL_ONE,
                            GL_ONE_MINUS_DST_ALPHA, GL_ONE);
	break;
      }
    }


    if(unlikely(current_frontface != rj->frontface)) {
      current_frontface = rj->frontface;
      glFrontFace(current_frontface == GLW_CW ? GL_CW : GL_CCW);
    }

    glDrawArrays(rj->primitive_type, rj->vertex_offset, rj->num_vertices);
  }
  if(current_blendmode != GLW_BLEND_NORMAL) {
    glBlendFuncSeparate(GL_SRC_COLOR, GL_ONE,
			GL_ONE_MINUS_DST_ALPHA, GL_ONE);
  }
  ts = arch_get_ts() - ts;
  static int hold;
  
  hold++;
  if(hold < 20)
    return;
#if 0
  static int cnt;
  static int64_t tssum;

  tssum += ts;
  cnt++;

  printf("%16d (%d) %d saved texloads\n", (int)ts, (int)(tssum/cnt),
         rs.texload_skips);
#endif
}
Exemple #27
0
void EmuThread::run()
{
	running = true;
	setCurrentThreadName("EmuThread");

	g_State.bEmuThreadStarted = true;

	host->UpdateUI();
	host->InitGL();

	glw->makeCurrent();

#ifndef USING_GLES2
	glewInit();
#endif
	NativeInitGraphics();

	INFO_LOG(BOOT, "Starting up hardware.");

	CoreParameter coreParameter;
	coreParameter.fileToStart = fileToStart.toStdString();
	coreParameter.enableSound = true;
	coreParameter.gpuCore = GPU_GLES;
	coreParameter.cpuCore = (CPUCore)g_Config.iCpuCore;
	coreParameter.enableDebugging = true;
	coreParameter.printfEmuLog = false;
	coreParameter.headLess = false;
	coreParameter.renderWidth = 480 * g_Config.iWindowZoom;
	coreParameter.renderHeight = 272 * g_Config.iWindowZoom;
	coreParameter.outputWidth = dp_xres;
	coreParameter.outputHeight = dp_yres;
	coreParameter.pixelWidth = pixel_xres;
	coreParameter.pixelHeight = pixel_yres;
	coreParameter.startPaused = !g_Config.bAutoRun;

	std::string error_string;
	if (!PSP_Init(coreParameter, &error_string))
	{
		ERROR_LOG(BOOT, "Error loading: %s", error_string.c_str());
		FinalShutdown();
		return;
	}

	LayoutGamepad(dp_xres, dp_yres);

	_dbg_update_();

	host->UpdateDisassembly();
	Core_EnableStepping(coreParameter.startPaused ? TRUE : FALSE);

	g_State.bBooted = true;
#ifdef _DEBUG
	host->UpdateMemView();
#endif
	host->BootDone();

	while(running) {
		//UpdateGamepad(*input_state);
		UpdateInputState(input_state);

		static const int mapping[12][2] = {
			{PAD_BUTTON_A, CTRL_CROSS},
			{PAD_BUTTON_B, CTRL_CIRCLE},
			{PAD_BUTTON_X, CTRL_SQUARE},
			{PAD_BUTTON_Y, CTRL_TRIANGLE},
			{PAD_BUTTON_UP, CTRL_UP},
			{PAD_BUTTON_DOWN, CTRL_DOWN},
			{PAD_BUTTON_LEFT, CTRL_LEFT},
			{PAD_BUTTON_RIGHT, CTRL_RIGHT},
			{PAD_BUTTON_LBUMPER, CTRL_LTRIGGER},
			{PAD_BUTTON_RBUMPER, CTRL_RTRIGGER},
			{PAD_BUTTON_START, CTRL_START},
			{PAD_BUTTON_SELECT, CTRL_SELECT},
		};

		for (int i = 0; i < 12; i++) {
            if (input_state->pad_buttons_down & mapping[i][0]) {
				__CtrlButtonDown(mapping[i][1]);
			}
            if (input_state->pad_buttons_up & mapping[i][0]) {
				__CtrlButtonUp(mapping[i][1]);
			}
		}
		__CtrlSetAnalog(input_state->pad_lstick_x, input_state->pad_lstick_y);

		EndInputState(input_state);

		glstate.Restore();
		glViewport(0, 0, pixel_xres, pixel_yres);
		Matrix4x4 ortho;
		ortho.setOrtho(0.0f, dp_xres, dp_yres, 0.0f, -1.0f, 1.0f);
		glsl_bind(UIShader_Get());
		glUniformMatrix4fv(UIShader_Get()->u_worldviewproj, 1, GL_FALSE, ortho.getReadPtr());


		ReapplyGfxState();

		Core_Run();

		// Hopefully coreState is now CORE_NEXTFRAME
		if (coreState == CORE_NEXTFRAME) {
			// set back to running for the next frame
			coreState = CORE_RUNNING;
		}

		fbo_unbind();

		UIShader_Prepare();

		uiTexture->Bind(0);

		glViewport(0, 0, pixel_xres, pixel_yres);

		ui_draw2d.Begin(DBMODE_NORMAL);

		//if (g_Config.bShowTouchControls)
		//	DrawGamepad(ui_draw2d);

		glsl_bind(UIShader_Get());
		ui_draw2d.End();
		ui_draw2d.Flush(UIShader_Get());


		// Tiled renderers like PowerVR should benefit greatly from this. However - seems I can't call it?
#if defined(USING_GLES2)
		bool hasDiscard = false;  // TODO
		if (hasDiscard) {
			//glDiscardFramebuffer(GL_COLOR_EXT | GL_DEPTH_EXT | GL_STENCIL_EXT);
		}
#endif

		glw->swapBuffers();
	}
	glw->doneCurrent();
}
Exemple #28
0
void
glw_program_set_modelview(glw_backend_root_t *gbr, const glw_rctx_t *rc)
{
  const float *m = rc ? glw_mtx_get(rc->rc_mtx) : glw_identitymtx;
  glUniformMatrix4fv(gbr->gbr_current->gp_uniform_modelview, 1, 0, m);
}
Exemple #29
0
void * glclient_thread(void * arg)
{
  server_thread_args_t * a = (server_thread_args_t *)arg;
  static graphics_context_t gc;

  static struct js_event joy;
  int joy_fd;
  static char button[32];

  glclient_context_t *glcc = a->user_context_ptr;

  joy_fd = open(glcc->joy_dev, O_RDONLY);
  if (joy_fd == -1)
  {
    printf("Error: Joystick device open\n");
  }
  if (joy_fd != -1)
  {
    fcntl(joy_fd, F_SETFL, O_NONBLOCK);
  }

  gls_init(a);

  gls_cmd_get_context();
  gc.screen_width = glsc_global.screen_width;
  gc.screen_height = glsc_global.screen_height;
  printf("width:%d height:%d\n",glsc_global.screen_width,glsc_global.screen_height);
  init_gl(&gc);

  float aspect = (float)gc.screen_width / (float)gc.screen_height;

  mat_perspective(proj_mat, aspect, 0.1f, 1024.0f, 60.0f);
  glUniform4fv(gc.uloc_light, 1, light_pos);

  srand(0x12345678);
  int j;
  for (j = 0; j < 1024; j++)
  {
    obj[j].z = randf() * 8.0f - 10.0f;
    obj[j].x = (randf() * 2.0f - 1.0f) * obj[j].z;
    obj[j].y = (randf() * 1.0f - 0.5f) * obj[j].z;
    obj[j].dx = randf() * 0.0f - 0.0f;
    obj[j].dy = randf() * 0.0f - 0.0f;
    obj[j].dz = randf() * 0.0f - 0.0f;
    obj[j].rx = randf() * 6.28;
    obj[j].ry = randf() * 6.28;
    obj[j].rz = randf() * 6.28;
    obj[j].drx = randf() * 0.1f - 0.05f;
    obj[j].dry = randf() * 0.1f - 0.05f;
    obj[j].drz = randf() * 0.1f - 0.05f;
  }

  float x = 1.57f;
  float y = 0.0f;
  float z = -2.0f;
  int k = 1;

  int i;
  for (i = 0; i < 432000; i++)
  {
    struct timeval times, timee;
    gettimeofday(&times, NULL);

    if (joy_fd != -1)
    {
      while (read(joy_fd, &joy, sizeof(struct js_event)) == sizeof(struct js_event))
      {
        if ((joy.type & JS_EVENT_BUTTON) == JS_EVENT_BUTTON)
        {
          button[joy.number] = joy.value;
        }
      }

      if (button[4] > 0)
      {
        y += 0.01f;
      }
      if (button[6] > 0)
      {
        y += -0.01f;
      }
      if (button[5] > 0)
      {
        x += 0.01f * aspect;
      }
      if (button[7] > 0)
      {
        x += -0.01f * aspect;
      }
      if (button[12] > 0)
      {
        z += -0.01f;
      }
      if (button[13] > 0)
      {
        k++;
        k = (k > 45) ? 45 : k;
      }
      if (button[14] > 0)
      {
        z += 0.01f;
      }
      if (button[15] > 0)
      {
        k--;
        k = (k < 1) ? 1 : k;
      }
    }

    glUseProgram(gc.program);
    glBindBuffer(GL_ARRAY_BUFFER, gc.vbo_pos);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, gc.vbo_ind);
    glEnableVertexAttribArray(gc.vloc_pos);
    glEnableVertexAttribArray(gc.vloc_nor);
    glEnableVertexAttribArray(gc.vloc_tex);

    glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    for (j = 0; j < k; j++)
    {
      obj[j].rx += obj[j].drx;
      obj[j].ry += obj[j].dry;
      obj[j].rz += obj[j].drz;

      if (j == 0)
      {
        obj[j].x = 0.0f;
        obj[j].y = 0.0f;
        obj[j].z = z;
        obj[j].rx = -y;
        obj[j].ry = x;
        obj[j].rz = 0.0f;
      }

      mat_identity(model_mat);
      mat_translate(model_mat, obj[j].x, obj[j].y, obj[j].z);
      mat_rotate_x(model_mat, obj[j].rx);
      mat_rotate_y(model_mat, obj[j].ry);
      mat_rotate_z(model_mat, obj[j].rz);

      mat_copy(nor_mat, model_mat);
      mat_invert(nor_mat);
      mat_transpose(nor_mat);
      glUniformMatrix4fv(gc.uloc_nor, 1, GL_FALSE, nor_mat);
      mat_copy(obj[j].nor_mat, nor_mat);

      mat_copy(modelproj_mat, proj_mat);
      mat_mul(modelproj_mat, model_mat);
      glUniformMatrix4fv(gc.uloc_model, 1, GL_FALSE, modelproj_mat);
      mat_copy(obj[j].modelproj_mat, modelproj_mat);

      glDrawElements(GL_TRIANGLES, sizeof(ind_model) / sizeof(GLushort), GL_UNSIGNED_SHORT, 0);
    }
    glDisableVertexAttribArray(gc.vloc_tex);
    glDisableVertexAttribArray(gc.vloc_nor);
    glDisableVertexAttribArray(gc.vloc_pos);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
    gls_cmd_flip(i);
    gettimeofday(&timee, NULL);
    //printf("%d:%f ms ", i, get_diff_time(times, timee) * 1000.0f);
  }
  glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  gls_cmd_flip(i);
  release_gl(&gc);
  gls_free();
  if (joy_fd != -1)
  {
    close(joy_fd);
  }
  pthread_exit(NULL);
}
void BlockParticleManager::RenderInstanced(bool noWorldOffset)
{
    glShader* pShader = m_pRenderer->GetShader(m_instanceShader);

    GLint in_position = glGetAttribLocation(pShader->GetProgramObject(), "in_position");
    GLint in_color = glGetAttribLocation(pShader->GetProgramObject(), "in_color");
    GLint in_model_matrix = glGetAttribLocation(pShader->GetProgramObject(), "in_model_matrix");

    int numBlockParticles = (int)m_vpBlockParticlesList.size();
    int numBlockParticlesRender = GetNumRenderableParticles(noWorldOffset);
    if (numBlockParticlesRender > 0)
    {
        float* newMatrices = new float[16 * numBlockParticlesRender];
        float* newColors = new float[4 * numBlockParticlesRender];

        int counter = 0;
        for (int i = 0; i < numBlockParticles; i++)
        {
            // If we are a emitter creation particle, don't render.
            if (m_vpBlockParticlesList[i]->m_createEmitters == true)
            {
                continue;
            }

            // If we are to be erased, don't render
            if (m_vpBlockParticlesList[i]->m_erase == true)
            {
                continue;
            }

            // If we are rendering the special viewport particles and our parent particle effect viewport flag isn't set, don't render.
            if (noWorldOffset)
            {
                if (m_vpBlockParticlesList[i]->m_pParent == NULL ||
                        m_vpBlockParticlesList[i]->m_pParent->m_pParent == NULL ||
                        m_vpBlockParticlesList[i]->m_pParent->m_pParent->m_renderNoWoldOffsetViewport == false)
                {
                    continue;
                }
            }

            newColors[counter + 0] = m_vpBlockParticlesList[i]->m_currentRed;
            newColors[counter + 1] = m_vpBlockParticlesList[i]->m_currentGreen;
            newColors[counter + 2] = m_vpBlockParticlesList[i]->m_currentBlue;
            newColors[counter + 3] = m_vpBlockParticlesList[i]->m_currentAlpha;
            counter += 4;
        }
        counter = 0;
        for (int i = 0; i < numBlockParticles; i++)
        {
            // If we are a emitter creation particle, don't render.
            if (m_vpBlockParticlesList[i]->m_createEmitters == true)
            {
                continue;
            }

            // If we are to be erased, don't render
            if (m_vpBlockParticlesList[i]->m_erase == true)
            {
                continue;
            }

            // If we are rendering the special viewport particles and our parent particle effect viewport flag isn't set, don't render.
            if (noWorldOffset)
            {
                if (m_vpBlockParticlesList[i]->m_pParent == NULL ||
                        m_vpBlockParticlesList[i]->m_pParent->m_pParent == NULL ||
                        m_vpBlockParticlesList[i]->m_pParent->m_pParent->m_renderNoWoldOffsetViewport == false)
                {
                    continue;
                }
            }

            m_vpBlockParticlesList[i]->CalculateWorldTransformMatrix();

            if (noWorldOffset)
            {
                newMatrices[counter + 0] = m_vpBlockParticlesList[i]->m_worldMatrix_NoPositionOffset.m[0];
                newMatrices[counter + 1] = m_vpBlockParticlesList[i]->m_worldMatrix_NoPositionOffset.m[1];
                newMatrices[counter + 2] = m_vpBlockParticlesList[i]->m_worldMatrix_NoPositionOffset.m[2];
                newMatrices[counter + 3] = m_vpBlockParticlesList[i]->m_worldMatrix_NoPositionOffset.m[3];
                newMatrices[counter + 4] = m_vpBlockParticlesList[i]->m_worldMatrix_NoPositionOffset.m[4];
                newMatrices[counter + 5] = m_vpBlockParticlesList[i]->m_worldMatrix_NoPositionOffset.m[5];
                newMatrices[counter + 6] = m_vpBlockParticlesList[i]->m_worldMatrix_NoPositionOffset.m[6];
                newMatrices[counter + 7] = m_vpBlockParticlesList[i]->m_worldMatrix_NoPositionOffset.m[7];
                newMatrices[counter + 8] = m_vpBlockParticlesList[i]->m_worldMatrix_NoPositionOffset.m[8];
                newMatrices[counter + 9] = m_vpBlockParticlesList[i]->m_worldMatrix_NoPositionOffset.m[9];
                newMatrices[counter + 10] = m_vpBlockParticlesList[i]->m_worldMatrix_NoPositionOffset.m[10];
                newMatrices[counter + 11] = m_vpBlockParticlesList[i]->m_worldMatrix_NoPositionOffset.m[11];
                newMatrices[counter + 12] = m_vpBlockParticlesList[i]->m_worldMatrix_NoPositionOffset.m[12];
                newMatrices[counter + 13] = m_vpBlockParticlesList[i]->m_worldMatrix_NoPositionOffset.m[13];
                newMatrices[counter + 14] = m_vpBlockParticlesList[i]->m_worldMatrix_NoPositionOffset.m[14];
                newMatrices[counter + 15] = m_vpBlockParticlesList[i]->m_worldMatrix_NoPositionOffset.m[15];
            }
            else
            {
                newMatrices[counter + 0] = m_vpBlockParticlesList[i]->m_worldMatrix.m[0];
                newMatrices[counter + 1] = m_vpBlockParticlesList[i]->m_worldMatrix.m[1];
                newMatrices[counter + 2] = m_vpBlockParticlesList[i]->m_worldMatrix.m[2];
                newMatrices[counter + 3] = m_vpBlockParticlesList[i]->m_worldMatrix.m[3];
                newMatrices[counter + 4] = m_vpBlockParticlesList[i]->m_worldMatrix.m[4];
                newMatrices[counter + 5] = m_vpBlockParticlesList[i]->m_worldMatrix.m[5];
                newMatrices[counter + 6] = m_vpBlockParticlesList[i]->m_worldMatrix.m[6];
                newMatrices[counter + 7] = m_vpBlockParticlesList[i]->m_worldMatrix.m[7];
                newMatrices[counter + 8] = m_vpBlockParticlesList[i]->m_worldMatrix.m[8];
                newMatrices[counter + 9] = m_vpBlockParticlesList[i]->m_worldMatrix.m[9];
                newMatrices[counter + 10] = m_vpBlockParticlesList[i]->m_worldMatrix.m[10];
                newMatrices[counter + 11] = m_vpBlockParticlesList[i]->m_worldMatrix.m[11];
                newMatrices[counter + 12] = m_vpBlockParticlesList[i]->m_worldMatrix.m[12];
                newMatrices[counter + 13] = m_vpBlockParticlesList[i]->m_worldMatrix.m[13];
                newMatrices[counter + 14] = m_vpBlockParticlesList[i]->m_worldMatrix.m[14];
                newMatrices[counter + 15] = m_vpBlockParticlesList[i]->m_worldMatrix.m[15];
            }
            counter += 16;
        }

        glBindVertexArray(m_vertexArray);

        if (m_colourBuffer != -1)
        {
            glDeleteBuffers(1, &m_colourBuffer);
        }
        // Bind buffer for colors and copy data into buffer
        glGenBuffers(1, &m_colourBuffer);
        glBindBuffer(GL_ARRAY_BUFFER, m_colourBuffer);
        glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 4 * numBlockParticlesRender, newColors, GL_STATIC_READ);
        glEnableVertexAttribArray(in_color);
        glVertexAttribPointer(in_color, 4, GL_FLOAT, GL_FALSE, 4 * 4, 0);
        glVertexAttribDivisor(in_color, 1);

        if (m_matrixBuffer != -1)
        {
            glDeleteBuffers(1, &m_matrixBuffer);
        }
        // Bind buffer for matrix and copy data into buffer
        glGenBuffers(1, &m_matrixBuffer);
        glBindBuffer(GL_ARRAY_BUFFER, m_matrixBuffer);
        for (int i = 0; i < 4; i++)
        {
            glVertexAttribPointer(in_model_matrix + i,		// Location
                                  4, GL_FLOAT, GL_FALSE,	// vec4
                                  4 * 16,						// Stride
                                  reinterpret_cast<void *>(16 * i));		// Start offset

            glEnableVertexAttribArray(in_model_matrix + i);
            glVertexAttribDivisor(in_model_matrix + i, 1);
        }
        glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 16 * numBlockParticlesRender, newMatrices, GL_STATIC_READ);

        delete[] newColors;
        delete[] newMatrices;
    }

    // Render the block particle instances
    m_pRenderer->BeginGLSLShader(m_instanceShader);

    GLint projMatrixLoc = glGetUniformLocation(pShader->GetProgramObject(), "projMatrix");
    GLint viewMatrixLoc = glGetUniformLocation(pShader->GetProgramObject(), "viewMatrix");

    Matrix4x4 projMat;
    Matrix4x4 viewMat;
    m_pRenderer->GetProjectionMatrix(&projMat);
    m_pRenderer->GetModelViewMatrix(&viewMat);

    glUniformMatrix4fv(projMatrixLoc, 1, false, projMat.m);
    glUniformMatrix4fv(viewMatrixLoc, 1, false, viewMat.m);

    GLint in_light_position = glGetUniformLocation(pShader->GetProgramObject(), "in_light_position");
    GLint in_light_const_a = glGetUniformLocation(pShader->GetProgramObject(), "in_light_const_a");
    GLint in_light_linear_a = glGetUniformLocation(pShader->GetProgramObject(), "in_light_linear_a");
    GLint in_light_quad_a = glGetUniformLocation(pShader->GetProgramObject(), "in_light_quad_a");
    GLint in_light_ambient = glGetUniformLocation(pShader->GetProgramObject(), "in_light_ambient");
    GLint in_light_diffuse = glGetUniformLocation(pShader->GetProgramObject(), "in_light_diffuse");

    if (m_renderWireFrame)
    {
        m_pRenderer->SetLineWidth(1.0f);
        m_pRenderer->SetRenderMode(RM_WIREFRAME);
        m_pRenderer->SetCullMode(CM_NOCULL);
    }
    else
    {
        m_pRenderer->SetCullMode(CM_BACK);
        m_pRenderer->SetRenderMode(RM_SOLID);
    }

    m_pRenderer->EnableTransparency(BF_SRC_ALPHA, BF_ONE_MINUS_SRC_ALPHA);

    glDrawElementsInstanced(GL_QUADS, 24, GL_UNSIGNED_INT, indices, numBlockParticlesRender);

    m_pRenderer->DisableTransparency();

    m_pRenderer->EndGLSLShader(m_instanceShader);

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