Пример #1
0
void SetTransformation(ShaderPtr program, float time) {
  // Create transformation matrix
  // NOTE: glm matrices are declared column major !

  // identity
  auto transform = glm::mat3({
     1.0, 0.0, 0.0,
     0.0, 1.0, 0.0,
     0.0, 0.0, 1.0
  });

  // scale
  // transform *= glm::mat3({
  //    std::sin(time), 0.0, 0.0,
  //    0.0, std::sin(time), 0.0,
  //    0.0, 0.0, 1.0
  //  });

  // squash
  // transform *= glm::mat3({
  //   std::sin(time), 0.0, 0.0,
  //   0.0, std::cos(time), 0.0,
  //   0.0, 0.0, 1.0
  // });

  // rotate
  transform *= glm::mat3({
     std::cos(time), std::sin(time), 0.0,
     -std::sin(time), std::cos(time), 0.0,
     0.0, 0.0, 1.0
  });

  // translate
  // transform *= glm::mat3({
  //    1.0, 0.0, 0.0,
  //   0.0, 1.0, 0.0,
  //   std::sin(time)/2.0, std::cos(time)/2.0, 1.0
  // });

  // Rotate around top right corner
  // transform *= glm::mat3({
  //   // Move to origin
  //   1.0, 0.0, 0.0,
  //   0.0, 1.0, 0.0,
  //   1.0, 1.0, 1.0
  // }) * glm::mat3({
  //   // Rotate
  //   std::cos(time), std::sin(time), 0.0,
  //   -std::sin(time), std::cos(time), 0.0,
  //   0.0, 0.0, 1.0
  // }) * glm::mat3({
  //   // Move back
  //   1.0, 0.0, 0.0,
  //   0.0, 1.0, 0.0,
  //   -1.0, -1.0, 1.0
  // });

  // Send matrix value to program
  auto transform_uniform = program->GetUniformLocation("Transform");
  glUniformMatrix3fv(transform_uniform, 1, GL_FALSE, glm::value_ptr(transform));
}
Пример #2
0
		void program::uniform(const std::string& name, bool transpose, const glm::mat3& value) noexcept {
			glUniformMatrix3fv(resolve_uniform_location(name), 1, transpose, glm::value_ptr(value));
		}
Пример #3
0
	void UniformHandler::CalculateMeshUniform(const Uniform& sUniform, SPODMesh *pMesh, SPODNode *pNode)
	{
		switch(sUniform.getSemantic())
		{
		case eUsPosition:
			{
				glVertexAttribPointer(sUniform.getLocation(), 3, GL_FLOAT, GL_FALSE, pMesh->sVertex.nStride, pMesh->sVertex.pData);
				glEnableVertexAttribArray(sUniform.getLocation());
			}
			break;
		case eUsNormal:
			{
				glVertexAttribPointer(sUniform.getLocation(), 3, GL_FLOAT, GL_FALSE, pMesh->sNormals.nStride, pMesh->sNormals.pData);
				glEnableVertexAttribArray(sUniform.getLocation());
			}
			break;
		case eUsTangent:
			{
				glVertexAttribPointer(sUniform.getLocation(), 3, GL_FLOAT, GL_FALSE, pMesh->sTangents.nStride, pMesh->sTangents.pData);
				glEnableVertexAttribArray(sUniform.getLocation());
			}
			break;
		case eUsBinormal:
			{
				glVertexAttribPointer(sUniform.getLocation(), 2, GL_FLOAT, GL_FALSE, pMesh->sBinormals.nStride, pMesh->sBinormals.pData);
				glEnableVertexAttribArray(sUniform.getLocation());
			}
			break;
		case eUsUV:
			{
				glVertexAttribPointer(sUniform.getLocation(), 2, GL_FLOAT, GL_FALSE, pMesh->psUVW[0].nStride, pMesh->psUVW[0].pData);
				glEnableVertexAttribArray(sUniform.getLocation());
			}
			break;
		case eUsBoneIndex:
			{
				glVertexAttribPointer(sUniform.getLocation(), pMesh->sBoneIdx.n, GL_UNSIGNED_BYTE, GL_FALSE, pMesh->sBoneIdx.nStride, pMesh->sBoneIdx.pData);
				glEnableVertexAttribArray(sUniform.getLocation());
			}
			break;
		case eUsBoneWeight:
			{
				glVertexAttribPointer(sUniform.getLocation(), pMesh->sBoneWeight.n, GL_FLOAT, GL_FALSE, pMesh->sBoneWeight.nStride, pMesh->sBoneWeight.pData);
				glEnableVertexAttribArray(sUniform.getLocation());
			}
			break;
		case eUsWORLD:
			{
				glUniformMatrix4fv(sUniform.getLocation(), 1, GL_FALSE, m_mWorld.f);
			}
			break;
		case eUsWORLDI:
			{
				PVRTMat4 mWorldI;
				mWorldI =  m_mWorld.inverse();
				glUniformMatrix4fv(sUniform.getLocation(), 1, GL_FALSE, mWorldI.f);
			}
			break;
		case eUsWORLDIT:
			{
				PVRTMat3 mWorldIT;
				mWorldIT = m_mWorld.inverse().transpose();
				glUniformMatrix3fv(sUniform.getLocation(), 1, GL_FALSE, mWorldIT.f);
			}
			break;
		case eUsWORLDVIEW:
			{
				glUniformMatrix4fv(sUniform.getLocation(), 1, GL_FALSE, m_mWorldView.f);
			}
			break;
		case eUsWORLDVIEWI:
			{
				PVRTMat4 mWorldViewI;
				mWorldViewI = m_mWorldView.inverse();
				glUniformMatrix4fv(sUniform.getLocation(), 1, GL_FALSE, mWorldViewI.f);
			}
			break;
		case eUsWORLDVIEWIT:
			{
				PVRTMat3 mWorldViewIT;
				mWorldViewIT = m_mWorldView.inverse().transpose();
				glUniformMatrix3fv(sUniform.getLocation(), 1, GL_FALSE, mWorldViewIT.f);
			}
			break;
		case eUsWORLDVIEWPROJECTION:
			{
				glUniformMatrix4fv(sUniform.getLocation(), 1, GL_FALSE, m_mWorldViewProjection.f);
			}
			break;
		case eUsWORLDVIEWPROJECTIONI:
			{
				PVRTMat4 mWorldViewProjectionI = (m_mProjection * m_mWorldView ).inverse();
				glUniformMatrix4fv(sUniform.getLocation(), 1, GL_FALSE, mWorldViewProjectionI.f);
			}
			break;
		case eUsWORLDVIEWPROJECTIONIT:
			{
				PVRTMat3 mWorldViewProjectionIT = (m_mProjection * m_mWorldView).inverse().transpose();
				glUniformMatrix3fv(sUniform.getLocation(), 1, GL_FALSE, mWorldViewProjectionIT.f);
			}
			break;
		case eUsLIGHTPOSMODEL:
			{
				// Passes the light position in eye space to the shader
				Light* pLight = m_pLightManager->get(sUniform.getIdx());
				switch(pLight->getType())
				{
				case eLightTypePoint:
					{
						PVRTVec4 vLightPosModel = m_mWorld.inverse() * ((LightPoint*)pLight)->getPositionPVRTVec4() ;
						glUniform3f(sUniform.getLocation(),
							vLightPosModel.x,
							vLightPosModel.y,
							vLightPosModel.z);
					}
					break;
				case eLightTypePODPoint:
					{
						PVRTVec4 vLightPosModel = m_mWorld.inverse() * ((LightPODPoint*)pLight)->getPositionPVRTVec4() ;
						glUniform3f(sUniform.getLocation(),
							vLightPosModel.x,
							vLightPosModel.y,
							vLightPosModel.z);
					}
					break;
				default:
					{	// hack for directional lights
						// take the light direction and multiply it by a really big negative number
						// if you hit this code then the types of your lights do not match the types expected by your shaders
						PVRTVec4 vLightPosModel = (((LightDirectional*)pLight)->getDirectionPVRTVec4()*c_fFarDistance) ;
						vLightPosModel.w = f2vt(1.0f);
						vLightPosModel = m_mWorld * vLightPosModel;
						glUniform3f(sUniform.getLocation(),
							vLightPosModel.x,
							vLightPosModel.y,
							vLightPosModel.z);
					}
				}
			}
			break;
		case eUsOBJECT:
			{
				// Scale
				PVRTMat4 mObject = m_psScene->GetScalingMatrix(*pNode);
				// Rotation
				mObject = m_psScene->GetRotationMatrix(*pNode) * mObject;
				// Translation
				mObject = m_psScene->GetTranslationMatrix(*pNode) * mObject;

				glUniformMatrix4fv(sUniform.getLocation(), 1, GL_FALSE, mObject.f);
			}
			break;
		case eUsOBJECTI:
			{
				if(!getFlag(eUsOBJECT))
				{
					// Scale
					m_mObject = m_psScene->GetScalingMatrix(*pNode);
					// Rotation
					m_mObject = m_psScene->GetRotationMatrix(*pNode) * m_mObject;
					// Translation
					m_mObject = (m_psScene->GetTranslationMatrix(*pNode) * m_mObject);
					setFlag(eUsOBJECT);
				}
				m_mObjectI = m_mObject.inverse();

				glUniformMatrix4fv(sUniform.getLocation(), 1, GL_FALSE, m_mObjectI.f);
			}
			break;
		case eUsOBJECTIT:
			{
				if(!getFlag(eUsOBJECTI))
				{
					if(!getFlag(eUsOBJECT))
					{
						// Scale
						m_mObject = m_psScene->GetScalingMatrix(*pNode);
						// Rotation
						m_mObject = m_psScene->GetRotationMatrix(*pNode) * m_mObject;
						// Translation
						m_mObject = (m_psScene->GetTranslationMatrix(*pNode) * m_mObject);
						setFlag(eUsOBJECT);
					}
					m_mObjectI = m_mObject.inverse();
					setFlag(eUsOBJECTI);
				}

				m_mObjectIT = PVRTMat3(m_mObjectI).transpose();

				glUniformMatrix3fv(sUniform.getLocation(), 1, GL_FALSE, m_mObjectIT.f);
			}
			break;
		case eUsLIGHTDIRMODEL:
			{
				Light* pLight = m_pLightManager->get(sUniform.getIdx());
				switch(pLight->getType())
				{
				case eLightTypeDirectional:
					{
						// Passes the light direction in model space to the shader
						PVRTVec4 vLightDirectionModel,
							vLightDirection =((LightDirectional*)pLight)->getDirectionPVRTVec4();
						vLightDirectionModel = m_mWorld.inverse() * vLightDirection ;
						glUniform3f(sUniform.getLocation(), vLightDirectionModel.x, vLightDirectionModel.y, vLightDirectionModel.z);
					}
				case eLightTypePODDirectional:
					{
						// Passes the light direction in model space to the shader
						PVRTVec4 vLightDirectionModel,
							vLightDirection =((LightPODDirectional*)pLight)->getDirectionPVRTVec4();
						vLightDirectionModel = m_mWorld.inverse() * vLightDirection ;
						glUniform3f(sUniform.getLocation(), vLightDirectionModel.x, vLightDirectionModel.y, vLightDirectionModel.z);
					}
				default:
					{	// could mimic point lights
						// calculate vector between light position and mesh

						// implemented by getting hold of the nice centre point I calculated for all these meshes and using this point
					}
				}
			}
			break;
		case eUsEYEPOSMODEL:
			{	
				m_vEyePositionModel = m_mWorld.inverse() * PVRTVec4(m_vEyePositionWorld,VERTTYPE(1.0f));
				glUniform3f(sUniform.getLocation(), m_vEyePositionModel.x, m_vEyePositionModel.y, m_vEyePositionModel.z);
			}
			break;
		default:
			{	// something went wrong
				ConsoleLog::inst().log("Error: non-mesh uniform being interpreted as mesh uniform\n");
				return;
			}
		}
	}
Пример #4
0
 void Program::SetUniform(const string &name, const mat3 &x) const
 {
     glUniformMatrix3fv(mUniformLocations.find(name)->second, 1, GL_FALSE, (float*)&x);
 }
Пример #5
0
void GLSLProgram::UniformMat3Array( unsigned int uniform_id, unsigned int count, const float* mat )
{
    glUniformMatrix3fv( uniforms[ uniform_id ], count, GL_FALSE, mat );
}
Пример #6
0
void CShaderProgram::setUniform(GLint location, const glm::mat3& m)
{
    setActive();
    glUniformMatrix3fv(location, 1, GL_FALSE, glm::value_ptr(m));
}
void ScreenSpaceAmbientOcclusionManager::generate_ssao_texture(Scene * scene) {
    //Render scene normals and depth to a texture
    glViewport(0, 0, viewport_width, viewport_height);

    Matrix4D view = scene->set_view();
    Matrix4D projection = scene->set_projection();
    Matrix3D normal = glm::inverseTranspose(glm::mat3(view));

    glBindFramebuffer(GL_DRAW_FRAMEBUFFER, frame_buffer_object);
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, normal_depth_texture, 0);
    check_frame_buffer();

    glClearColor(0.f, 0.f, 0.f, 0.f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    
    shaders.select_shader(NORMAL_DEPTH_TEXTURE);

    uint program = shaders.get_program_id(NORMAL_DEPTH_TEXTURE);

    GLint projection_location = glGetUniformLocation(program, "projection");
    glUniformMatrix4fv(projection_location, 1, GL_FALSE, &projection[0][0]);

    GLint view_location = glGetUniformLocation(program, "view");
    glUniformMatrix4fv(view_location, 1, GL_FALSE, &view[0][0]);

    GLint normal_matrix_location = glGetUniformLocation(program, "normal_matrix");
    glUniformMatrix3fv(normal_matrix_location, 1, GL_FALSE, &normal[0][0]);

    scene->plain_render(view, program);
    scene->render_floor(view, program);

    shaders.select_shader(-1);

    glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);

    glBindTexture(GL_TEXTURE_2D, normal_depth_texture);
    glGenerateMipmap(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, 0);
    
    //Render SSAO to a texture
    glViewport(0, 0, viewport_width, viewport_height);
   
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    view = Matrix4D(1.0);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);
    projection = glm::ortho(-1.0, 1.0, -1.0, 1.0);

    glBindFramebuffer(GL_DRAW_FRAMEBUFFER, frame_buffer_object);
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, ssao_texture, 0);
    check_frame_buffer();

    glClearColor(0.f, 0.f, 0.f, 0.f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    shaders.select_shader(separable ? SEPARABLE_SSAO : SSAO_TEXTURE);

    glActiveTexture(GL_TEXTURE0);
    bind_normal_depth_texture();

    glActiveTexture(GL_TEXTURE1);
    glBindTexture(GL_TEXTURE_2D, textures.getID(noise));

    program = shaders.get_program_id(separable ? SEPARABLE_SSAO : SSAO_TEXTURE);
    GLint sampler_reference = glGetUniformLocation(program, "sampler");
    glUniform1i(sampler_reference, 0);

    GLint noise_reference = glGetUniformLocation(program, "noise");
    glUniform1i(noise_reference, 1);

    GLint viewport_width_reference = glGetUniformLocation(program, "viewport_width");
    glUniform1f(viewport_width_reference, viewport_width);

    GLint viewport_height_reference = glGetUniformLocation(program, "viewport_height");
    glUniform1f(viewport_height_reference, viewport_height);

    GLint radius_reference = glGetUniformLocation(program, "radius_modifier");
    glUniform1f(radius_reference, radius);

    projection_location = glGetUniformLocation(program, "projection");
    glUniformMatrix4fv(projection_location, 1, GL_FALSE, &projection[0][0]);

    view_location = glGetUniformLocation(program, "view");
    glUniformMatrix4fv(view_location, 1, GL_FALSE, &view[0][0]);

    glColor3f(1.0, 1.0, 1.0);
    glBegin(GL_QUADS);
        glVertex3f(-1, -1, -0.5);
        glVertex3f(1, -1, -0.5);
        glVertex3f(1, 1, -0.5);
        glVertex3f(-1, 1, -0.5);
    glEnd();

    shaders.select_shader(-1);

    glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);

    glBindTexture(GL_TEXTURE_2D, ssao_texture);
    glGenerateMipmap(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, 0);

    //Blur the SSAO texture in X direction
    glViewport(0, 0, viewport_width, viewport_height);
   
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);

    glBindFramebuffer(GL_DRAW_FRAMEBUFFER, frame_buffer_object);
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, blurred_ssao_texture_x, 0);
    check_frame_buffer();

    glClearColor(0.f, 0.f, 0.f, 0.f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    shaders.select_shader(GAUSSIAN_X);

    glActiveTexture(GL_TEXTURE0);
    bind_ssao_texture();

    program = shaders.get_program_id(GAUSSIAN_X);

    sampler_reference = glGetUniformLocation(program, "sampler");
    glUniform1i(sampler_reference, 0);

    viewport_width_reference = glGetUniformLocation(program, "viewport_width");
    glUniform1f(viewport_width_reference, viewport_width);

    viewport_height_reference = glGetUniformLocation(program, "viewport_height");
    glUniform1f(viewport_height_reference, viewport_height);

    projection_location = glGetUniformLocation(program, "projection");
    glUniformMatrix4fv(projection_location, 1, GL_FALSE, &projection[0][0]);

    view_location = glGetUniformLocation(program, "view");
    glUniformMatrix4fv(view_location, 1, GL_FALSE, &view[0][0]);

    glColor3f(1.0, 1.0, 1.0);
    glBegin(GL_QUADS);
        glVertex3f(-1, -1, -0.5);
        glVertex3f(1, -1, -0.5);
        glVertex3f(1, 1, -0.5);
        glVertex3f(-1, 1, -0.5);
    glEnd();

    shaders.select_shader(-1);

    glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);

    glBindTexture(GL_TEXTURE_2D, blurred_ssao_texture_x);
    glGenerateMipmap(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, 0);

    //Blur the SSAO texture in Y direction
    glViewport(0, 0, viewport_width, viewport_height);
   
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);

    glBindFramebuffer(GL_DRAW_FRAMEBUFFER, frame_buffer_object);
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, blurred_ssao_texture_xy, 0);
    check_frame_buffer();

    glClearColor(0.f, 0.f, 0.f, 0.f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    shaders.select_shader(GAUSSIAN_Y);

    glActiveTexture(GL_TEXTURE0);
    bind_blurred_ssao_texture_x();

    program = shaders.get_program_id(GAUSSIAN_Y);

    sampler_reference = glGetUniformLocation(program, "sampler");
    glUniform1i(sampler_reference, 0);

    viewport_width_reference = glGetUniformLocation(program, "viewport_width");
    glUniform1f(viewport_width_reference, viewport_width);

    viewport_height_reference = glGetUniformLocation(program, "viewport_height");
    glUniform1f(viewport_height_reference, viewport_height);

    projection_location = glGetUniformLocation(program, "projection");
    glUniformMatrix4fv(projection_location, 1, GL_FALSE, &projection[0][0]);

    view_location = glGetUniformLocation(program, "view");
    glUniformMatrix4fv(view_location, 1, GL_FALSE, &view[0][0]);

    glColor3f(1.0, 1.0, 1.0);
    glBegin(GL_QUADS);
        glVertex3f(-1, -1, -0.5);
        glVertex3f(1, -1, -0.5);
        glVertex3f(1, 1, -0.5);
        glVertex3f(-1, 1, -0.5);
    glEnd();

    shaders.select_shader(-1);

    glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);

    glBindTexture(GL_TEXTURE_2D, blurred_ssao_texture_xy);
    glGenerateMipmap(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, 0);
}
Пример #8
0
GLUSboolean update(GLUSfloat time)
{
    static GLfloat angle = 0.0f;

    GLfloat modelViewMatrix[16];

    GLfloat viewMatrix[16];
    GLfloat shadowProjectionMatrix[16];
    GLfloat modelMatrix[16];
    GLfloat normalMatrix[9];

    // This shadow plane represents mathematically the background plane
    GLfloat shadowPlane[4] = {0.0f, 0.0f, 1.0f, 5.0f};

    glusMatrix4x4LookAtf(viewMatrix, g_cameraPosition[0], g_cameraPosition[1], g_cameraPosition[2], 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f);

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    //
    // Render the scene.
    //

    glUseProgram(g_program.program);

    glUniformMatrix4fv(g_viewMatrixLocation, 1, GL_FALSE, viewMatrix);

    // Background Plane

    glusMatrix4x4Identityf(modelMatrix);
    glusMatrix4x4Translatef(modelMatrix, 0.0f, 0.0f, -5.0f);
    glusMatrix4x4Multiplyf(modelViewMatrix, viewMatrix, modelMatrix);
    glusMatrix4x4ExtractMatrix3x3f(normalMatrix, modelViewMatrix);

    glUniformMatrix4fv(g_modelMatrixLocation, 1, GL_FALSE, modelMatrix);
    glUniformMatrix3fv(g_normalMatrixLocation, 1, GL_FALSE, normalMatrix);
    glUniform4f(g_colorLocation, 0.0f, 0.5f, 0.0f, 1.0f);

    glBindVertexArray(g_vaoBackground);
    glDrawElements(GL_TRIANGLES, g_numberIndicesBackground, GL_UNSIGNED_INT, 0);

    //
    // Render the planar shadow
    //

    glUseProgram(g_programShadow.program);

    glUniformMatrix4fv(g_viewMatrixShadowLocation, 1, GL_FALSE, viewMatrix);

    // Torus projected as a shadow

    glusMatrix4x4PlanarShadowDirectionalLightf(shadowProjectionMatrix, shadowPlane, g_lightDirection);
    glUniformMatrix4fv(g_shadowProjectionMatrixShadowLocation, 1, GL_FALSE, shadowProjectionMatrix);

    glusMatrix4x4Identityf(modelMatrix);
    glusMatrix4x4RotateRzRxRyf(modelMatrix, 0.0f, 0.0f, angle);
    glUniformMatrix4fv(g_modelMatrixShadowLocation, 1, GL_FALSE, modelMatrix);

    glBindVertexArray(g_vaoShadow);

    // Overwrite the background plane
    glDisable(GL_DEPTH_TEST);

    glDrawElements(GL_TRIANGLES, g_numberIndicesTorus, GL_UNSIGNED_INT, 0);

    glEnable(GL_DEPTH_TEST);

    // Torus with color

    glUseProgram(g_program.program);

    glusMatrix4x4Multiplyf(modelViewMatrix, viewMatrix, modelMatrix);
    glusMatrix4x4ExtractMatrix3x3f(normalMatrix, modelViewMatrix);

    glUniformMatrix4fv(g_modelMatrixLocation, 1, GL_FALSE, modelMatrix);
    glUniformMatrix3fv(g_normalMatrixLocation, 1, GL_FALSE, normalMatrix);
    glUniform4f(g_colorLocation, 0.33f, 0.0f, 0.5f, 1.0f);

    glBindVertexArray(g_vao);
    glDrawElements(GL_TRIANGLES, g_numberIndicesTorus, GL_UNSIGNED_INT, 0);

    //

    angle += 20.0f * time;

    return GLUS_TRUE;
}
Пример #9
0
bool setup_unistate(int sidx, const ShaderProg *sdr, int loc)
{
	if(loc < 0 || sidx < 0 || sidx >= (int)state.size()) {
		return false;
	}

	CHECKGLERR;
	glUseProgram(sdr->get_id());
	CHECKGLERR;

	switch(state[sidx].type) {
	case ST_INT:
		glUniform1iv(loc, 1, state[sidx].ival);
		break;
	case ST_INT2:
		glUniform2iv(loc, 1, state[sidx].ival);
		break;
	case ST_INT3:
		glUniform3iv(loc, 1, state[sidx].ival);
		break;
	case ST_INT4:
		glUniform4iv(loc, 1, state[sidx].ival);
		break;

	case ST_FLOAT:
		glUniform1fv(loc, 1, state[sidx].fval);
		break;
	case ST_FLOAT2:
		glUniform2fv(loc, 1, state[sidx].fval);
		break;
	case ST_FLOAT3:
		glUniform3fv(loc, 1, state[sidx].fval);
		break;
	case ST_FLOAT4:
		glUniform4fv(loc, 1, state[sidx].fval);
		break;

	case ST_MATRIX3:
#ifdef GL_ES_VERSION_2_0
		{
			float tmat[9], *ptr = tmat;
			for(int i=0; i<3; i++) {
				for(int j=0; j<3; j++) {
					*ptr++ = state[sidx].fval[j * 3 + i];
				}
			}
			glUniformMatrix3fv(loc, 1, GL_FALSE, tmat);
		}
#else
		glUniformMatrix3fv(loc, 1, state[sidx].transpose, state[sidx].fval);
#endif
		break;

	case ST_MATRIX4:
#ifdef GL_ES_VERSION_2_0
		{
			float tmat[16], *ptr = tmat;
			for(int i=0; i<4; i++) {
				for(int j=0; j<4; j++) {
					*ptr++ = state[sidx].fval[j * 4 + i];
				}
			}
			glUniformMatrix4fv(loc, 1, GL_FALSE, tmat);
		}
#else
		glUniformMatrix4fv(loc, 1, state[sidx].transpose, state[sidx].fval);
#endif
		break;

	default:
		return false;
	}

	CHECKGLERR;
	return true;
}
Пример #10
0
 // ------------------------------------------------------------------------
 void Shader::setMat3( const std::string& p_name, const glm::mat3& p_mat ) const {
     glUniformMatrix3fv( glGetUniformLocation( m_program, p_name.c_str( ) ), 1, GL_FALSE, glm::value_ptr( p_mat ) );
 }
Пример #11
0
void
EGL2DescriptorSet::apply(const EGL2Program& shaderObject) noexcept
{
	for (auto& it : _activeUniformSets)
	{
		auto type = it->getGraphicsParam()->getType();
		auto location = it->getGraphicsParam()->getBindingPoint();
		switch (type)
		{
		case GraphicsUniformType::GraphicsUniformTypeBool:
			GL_CHECK(glUniform1i(location, it->getBool()));
			break;
		case GraphicsUniformType::GraphicsUniformTypeInt:
			GL_CHECK(glUniform1i(location, it->getInt()));
			break;
		case GraphicsUniformType::GraphicsUniformTypeInt2:
			GL_CHECK(glUniform2iv(location, 1, (GLint*)it->getInt2().ptr()));
			break;
		case GraphicsUniformType::GraphicsUniformTypeInt3:
			GL_CHECK(glUniform3iv(location, 1, (GLint*)it->getInt3().ptr()));
			break;
		case GraphicsUniformType::GraphicsUniformTypeInt4:
			GL_CHECK(glUniform4iv(location, 1, (GLint*)it->getInt4().ptr()));
			break;
		case GraphicsUniformType::GraphicsUniformTypeFloat:
			GL_CHECK(glUniform1f(location, it->getFloat()));
			break;
		case GraphicsUniformType::GraphicsUniformTypeFloat2:
			GL_CHECK(glUniform2fv(location, 1, it->getFloat2().ptr()));
			break;
		case GraphicsUniformType::GraphicsUniformTypeFloat3:
			GL_CHECK(glUniform3fv(location, 1, it->getFloat3().ptr()));
			break;
		case GraphicsUniformType::GraphicsUniformTypeFloat4:
			GL_CHECK(glUniform4fv(location, 1, it->getFloat4().ptr()));
			break;
		case GraphicsUniformType::GraphicsUniformTypeFloat3x3:
			GL_CHECK(glUniformMatrix3fv(location, 1, GL_FALSE, it->getFloat3x3().ptr()));
			break;
		case GraphicsUniformType::GraphicsUniformTypeFloat4x4:
			GL_CHECK(glUniformMatrix4fv(location, 1, GL_FALSE, it->getFloat4x4().ptr()));
			break;
		case GraphicsUniformType::GraphicsUniformTypeIntArray:
			GL_CHECK(glUniform1iv(location, it->getIntArray().size(), it->getIntArray().data()));
			break;
		case GraphicsUniformType::GraphicsUniformTypeInt2Array:
			GL_CHECK(glUniform2iv(location, it->getInt2Array().size(), (GLint*)it->getInt2Array().data()));
			break;
		case GraphicsUniformType::GraphicsUniformTypeInt3Array:
			GL_CHECK(glUniform3iv(location, it->getInt3Array().size(), (GLint*)it->getInt3Array().data()));
			break;
		case GraphicsUniformType::GraphicsUniformTypeInt4Array:
			GL_CHECK(glUniform4iv(location, it->getInt4Array().size(), (GLint*)it->getInt4Array().data()));
			break;
		case GraphicsUniformType::GraphicsUniformTypeFloatArray:
			GL_CHECK(glUniform1fv(location, it->getFloatArray().size(), (GLfloat*)it->getFloatArray().data()));
			break;
		case GraphicsUniformType::GraphicsUniformTypeFloat2Array:
			GL_CHECK(glUniform2fv(location, it->getFloat2Array().size(), (GLfloat*)it->getFloat2Array().data()));
			break;
		case GraphicsUniformType::GraphicsUniformTypeFloat3Array:
			GL_CHECK(glUniform3fv(location, it->getFloat3Array().size(), (GLfloat*)it->getFloat3Array().data()));
			break;
		case GraphicsUniformType::GraphicsUniformTypeFloat4Array:
			GL_CHECK(glUniform4fv(location, it->getFloat4Array().size(), (GLfloat*)it->getFloat4Array().data()));
			break;
		case GraphicsUniformType::GraphicsUniformTypeFloat3x3Array:
			GL_CHECK(glUniformMatrix3fv(location, it->getFloat3x3Array().size(), GL_FALSE, (GLfloat*)it->getFloat3x3Array().data()));
			break;
		case GraphicsUniformType::GraphicsUniformTypeFloat4x4Array:
			GL_CHECK(glUniformMatrix4fv(location, it->getFloat4x4Array().size(), GL_FALSE, (GLfloat*)it->getFloat4x4Array().data()));
			break;
		case GraphicsUniformType::GraphicsUniformTypeSampler:
			assert(false);
			break;
		case GraphicsUniformType::GraphicsUniformTypeSamplerImage:
			{
				auto& texture = it->getTexture();
				if (texture)
				{
					auto gltexture = texture->downcast<EGL2Texture>();
					GL_CHECK(glActiveTexture(GL_TEXTURE0 + location));
					GL_CHECK(glBindTexture(gltexture->getTarget(), gltexture->getInstanceID()));
				}
			}
			break;
		case GraphicsUniformType::GraphicsUniformTypeCombinedImageSampler:
			{
				auto& texture = it->getTexture();
				if (texture)
				{
					auto gltexture = texture->downcast<EGL2Texture>();
					GL_CHECK(glActiveTexture(GL_TEXTURE0 + location));
					GL_CHECK(glBindTexture(gltexture->getTarget(), gltexture->getInstanceID()));
				}
			}
			break;
		case GraphicsUniformType::GraphicsUniformTypeStorageImage:
			{
				auto& texture = it->getTexture();
				if (texture)
				{
					auto gltexture = texture->downcast<EGL2Texture>();
					GL_CHECK(glActiveTexture(GL_TEXTURE0 + location));
					GL_CHECK(glBindTexture(gltexture->getTarget(), gltexture->getInstanceID()));
				}
			}
			break;
		case GraphicsUniformType::GraphicsUniformTypeStorageTexelBuffer:
		case GraphicsUniformType::GraphicsUniformTypeUniformTexelBuffer:
			GL_PLATFORM_LOG("Can't support TBO.");
			break;
		case GraphicsUniformType::GraphicsUniformTypeStorageBuffer:
		case GraphicsUniformType::GraphicsUniformTypeStorageBufferDynamic:
		case GraphicsUniformType::GraphicsUniformTypeUniformBuffer:
		case GraphicsUniformType::GraphicsUniformTypeUniformBufferDynamic:
			GL_PLATFORM_LOG("Can't support UBO.");
			break;
		case GraphicsUniformType::GraphicsUniformTypeInputAttachment:
			break;
		case GraphicsUniformType::GraphicsUniformTypeUInt:
		case GraphicsUniformType::GraphicsUniformTypeUInt2:
		case GraphicsUniformType::GraphicsUniformTypeUInt3:
		case GraphicsUniformType::GraphicsUniformTypeUInt4:
		case GraphicsUniformType::GraphicsUniformTypeUIntArray:
		case GraphicsUniformType::GraphicsUniformTypeUInt2Array:
		case GraphicsUniformType::GraphicsUniformTypeUInt3Array:
		case GraphicsUniformType::GraphicsUniformTypeUInt4Array:
			GL_PLATFORM_LOG("Can't support unsigned type.");
			break;
		default:
			break;
		}
	}
}
Пример #12
0
void RenderScene(void) {
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
    glUseProgram(shader);  
	static CStopWatch Timer;

	float angle = Timer.GetElapsedSeconds() * 3/7;
	GLfloat position[] = { 1.0f, 1.0f, .5f };
	GLfloat color[] = { 1.0f, 1.0f, 1.0f };
	GLfloat angle2 = 90.0f;

	GLfloat attenuation0 = 0.1f;
	GLfloat attenuation1 = 0.1f;
	GLfloat attenuation2 = 0.1f;

	GLfloat ambientColor[] = { 0.1f, 0.5f, 0.1f };
	GLfloat diffuseColor[] = { 1.0f, 1.0f, 0.0f };
	GLfloat specularColor[] = { 0.0f, 0.0f, 1.0f };
	GLfloat specularExponent = 100.0f;

	GLMatrixStack modelView;
	GLMatrixStack projection;

	M3DVector3f at={0,0,0};
    M3DVector3f up={0,0,1};
    M3DVector3f eye;

	eye[0] = 2 * cos(angle);
	eye[1] = 2 * sin(angle);
	eye[2] = 10;

    LookAt(cameraFrame,eye,at,up);

	GLGeometryTransform geometryPipeline;
	geometryPipeline.SetMatrixStacks(modelView,projection);
	projection.LoadMatrix(frustum.GetProjectionMatrix());

	M3DMatrix44f mCamera;
	cameraFrame.GetCameraMatrix(mCamera);
	modelView.LoadMatrix(mCamera);
	modelView.PushMatrix();

	
	for(int i=-10; i<=10; ++i)
		{
			glBegin(GL_LINES);
			glVertex3f(-10, i, 0);
			glVertex3f(10, i, 0);
			glEnd();
			glBegin(GL_LINES);
			glVertex3f(i, -10, 0);
			glVertex3f(i, 10, 0);
			glEnd();
		}

	modelView.PopMatrix();

	modelView.PushMatrix();
	modelView.Translate(0,0.0,0.0);

	glUniformMatrix4fv(MVMatrixLocation,1,GL_FALSE,geometryPipeline.GetModelViewProjectionMatrix());
	glUniformMatrix4fv(MVPMatrixLocation,1,GL_FALSE,geometryPipeline.GetModelViewMatrix());
	glUniformMatrix3fv(normalMatrixLocation,1,GL_FALSE,geometryPipeline.GetNormalMatrix());
	glUniform3fv(shaderPositionLocation, 1, position);
	glUniform3fv(shaderColorLocation, 1, color);
	glUniform1f(shaderAngleLocation, angle2);
	glUniform1f(shaderAttenuation0Location, attenuation0);
	glUniform1f(shaderAttenuation1Location, attenuation1);
	glUniform1f(shaderAttenuation2Location, attenuation2);
	glUniform3fv(shaderAmbientColorLocation, 1, ambientColor);
	glUniform3fv(shaderDiffuseColorLocation, 1, diffuseColor);
	glUniform3fv(shaderSpecularColorLocation, 1, specularColor);
	glUniform1f(shaderSpecularExponentLocation, specularExponent);

	GLuint vertex_buffer;
	glGenBuffers(1,&vertex_buffer);
	glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer);
	glBufferData(GL_ARRAY_BUFFER,n_vertices*sizeof(float)*7,&vertices[0],GL_STATIC_DRAW);
	if(glGetError()!=GL_NO_ERROR) {
   	fprintf(stderr,"error copying vertices\n");
	}
	glVertexAttribPointer(GLT_ATTRIBUTE_VERTEX,4,GL_FLOAT,GL_FALSE,sizeof(float)*7,(const GLvoid *)0);
	glVertexAttribPointer(GLT_ATTRIBUTE_NORMAL,3,GL_FLOAT,GL_FALSE,sizeof(float)*7,(const GLvoid *)(4*sizeof(float)) );
	glEnableVertexAttribArray(GLT_ATTRIBUTE_VERTEX);
	glEnableVertexAttribArray(GLT_ATTRIBUTE_NORMAL);

	GLuint faces_buffer;
	glGenBuffers(1,&faces_buffer);
	if(glGetError()!=GL_NO_ERROR) {
	fprintf(stderr,"faces_buffer invalid\n");
	}
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,faces_buffer);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER,n_faces*sizeof(GLuint)*3,&faces[0],GL_STATIC_DRAW);
	if(glGetError()!=GL_NO_ERROR) {
	fprintf(stderr,"error copying faces\n");
	}
	glDrawElements(GL_TRIANGLES,3*n_faces,GL_UNSIGNED_INT,0);

	modelView.PopMatrix();

	// Perform the buffer swap to display back buffer
	glUseProgram(0);
    glutSwapBuffers();
	glutPostRedisplay();
}
/*!****************************************************************************
 @Function		RenderScene
 @Return		bool		true if no error occured
 @Description	Main rendering loop function of the program. The shell will
				call this function every frame.
				eglSwapBuffers() will be performed by PVRShell automatically.
				PVRShell will also manage important OS events.
				Will also manage relevent OS events. The user has access to
				these events through an abstraction layer provided by PVRShell.
******************************************************************************/
bool OGLES3IntroducingPFX::RenderScene()
{
	// Clears the color and depth buffer
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	// Use the loaded effect
	m_pEffect->Activate();

	/*
		Calculates the frame number to animate in a time-based manner.
		Uses the shell function PVRShellGetTime() to get the time in milliseconds.
	*/
	unsigned long ulTime = PVRShellGetTime();
	unsigned long ulDeltaTime = ulTime - m_ulTimePrev;
	m_ulTimePrev	= ulTime;
	m_fFrame	+= (float)ulDeltaTime * DEMO_FRAME_RATE;

	if (m_fFrame > m_Scene.nNumFrame-1)
		m_fFrame = 0;

	// Sets the scene animation to this frame
	m_Scene.SetFrame(m_fFrame);

	{
		PVRTVec3	vFrom, vTo, vUp;
		VERTTYPE	fFOV;
		vUp.x = 0.0f;
		vUp.y = 1.0f;
		vUp.z = 0.0f;

		// We can get the camera position, target and field of view (fov) with GetCameraPos()
		fFOV = m_Scene.GetCameraPos(vFrom, vTo, 0) * 0.4f;

		/*
			We can build the world view matrix from the camera position, target and an up vector.
			For this we use PVRTMat4LookAtRH().
		*/
		m_mView = PVRTMat4::LookAtRH(vFrom, vTo, vUp);

		// Calculates the projection matrix
		bool bRotate = PVRShellGet(prefIsRotated) && PVRShellGet(prefFullScreen);
		m_mProjection = PVRTMat4::PerspectiveFovRH(fFOV, (float)PVRShellGet(prefWidth)/(float)PVRShellGet(prefHeight), CAM_NEAR, CAM_FAR, PVRTMat4::OGL, bRotate);
	}

	// Retrieve the list of required uniforms
	const CPVRTArray<SPVRTPFXUniform>& aUniforms = m_pEffect->GetUniformArray();

	/*
		A scene is composed of nodes. There are 3 types of nodes:
		- MeshNodes :
			references a mesh in the pMesh[].
			These nodes are at the beginning of the pNode[] array.
			And there are nNumMeshNode number of them.
			This way the .pod format can instantiate several times the same mesh
			with different attributes.
		- lights
		- cameras
		To draw a scene, you must go through all the MeshNodes and draw the referenced meshes.
	*/

	for (int i=0; i<(int)m_Scene.nNumMeshNode; i++)
	{
		SPODNode* pNode = &m_Scene.pNode[i];

		// Gets pMesh referenced by the pNode
		SPODMesh* pMesh = &m_Scene.pMesh[pNode->nIdx];

		glBindBuffer(GL_ARRAY_BUFFER, m_aiVboID[i]);

		// Gets the node model matrix
		PVRTMat4 mWorld;
		mWorld = m_Scene.GetWorldMatrix(*pNode);

		PVRTMat4 mWorldView;
		mWorldView = m_mView * mWorld;

		/*	
			Now we loop over the uniforms requested by the PFX file.
			Using the switch statement allows us to handle all of the required semantics
		*/
		for(unsigned int j = 0; j < aUniforms.GetSize(); ++j)
		{
			switch(aUniforms[j].nSemantic)
			{
			case ePVRTPFX_UsPOSITION:
				{
					glVertexAttribPointer(aUniforms[j].nLocation, 3, GL_FLOAT, GL_FALSE, pMesh->sVertex.nStride, pMesh->sVertex.pData);
					glEnableVertexAttribArray(aUniforms[j].nLocation);
				}
				break;
			case ePVRTPFX_UsNORMAL:
				{
					glVertexAttribPointer(aUniforms[j].nLocation, 3, GL_FLOAT, GL_FALSE, pMesh->sNormals.nStride, pMesh->sNormals.pData);
					glEnableVertexAttribArray(aUniforms[j].nLocation);
				}
				break;
			case ePVRTPFX_UsUV:
				{
					glVertexAttribPointer(aUniforms[j].nLocation, 2, GL_FLOAT, GL_FALSE, pMesh->psUVW[0].nStride, pMesh->psUVW[0].pData);
					glEnableVertexAttribArray(aUniforms[j].nLocation);
				}
				break;
			case ePVRTPFX_UsWORLDVIEWPROJECTION:
				{
					PVRTMat4 mWVP;

					// Passes the world-view-projection matrix (WVP) to the shader to transform the vertices
					mWVP = m_mProjection * mWorldView;
					glUniformMatrix4fv(aUniforms[j].nLocation, 1, GL_FALSE, mWVP.f);
				}
				break;
			case ePVRTPFX_UsWORLDVIEWIT:
				{
					PVRTMat4 mWorldViewI, mWorldViewIT;

					// Passes the inverse transpose of the world-view matrix to the shader to transform the normals
					mWorldViewI  = mWorldView.inverse();
					mWorldViewIT = mWorldViewI.transpose();

					PVRTMat3 WorldViewIT = PVRTMat3(mWorldViewIT);

					glUniformMatrix3fv(aUniforms[j].nLocation, 1, GL_FALSE, WorldViewIT.f);
				}
				break;
			case ePVRTPFX_UsLIGHTDIREYE:
				{
					// Reads the light direction from the scene.
					PVRTVec4 vLightDirection;
					PVRTVec3 vPos;
					vLightDirection = m_Scene.GetLightDirection(0);

					vLightDirection.x = -vLightDirection.x;
					vLightDirection.y = -vLightDirection.y;
					vLightDirection.z = -vLightDirection.z;

					/*
						Sets the w component to 0, so when passing it to glLight(), it is
						considered as a directional light (as opposed to a spot light).
					*/
					vLightDirection.w = 0;

					// Passes the light direction in eye space to the shader
					PVRTVec4 vLightDirectionEyeSpace;
					vLightDirectionEyeSpace = m_mView * vLightDirection;

					glUniform3f(aUniforms[j].nLocation, vLightDirectionEyeSpace.x, vLightDirectionEyeSpace.y, vLightDirectionEyeSpace.z);
				}
				break;
			case ePVRTPFX_UsTEXTURE:
				{
					// Set the sampler variable to the texture unit
					glUniform1i(aUniforms[j].nLocation, aUniforms[j].nIdx);
				}
				break;
			case eUsMYCUSTOMSCALE:
				{
					PVRTMat4 mxScale = PVRTMat4::Identity();
					glUniformMatrix4fv(aUniforms[j].nLocation, 1, GL_FALSE, mxScale.ptr());
				}
				break;
			}
		}

		/*
			Now that the model-view matrix is set and the materials ready,
			call another function to actually draw the mesh.
		*/
		DrawMesh(pMesh);
		glBindBuffer(GL_ARRAY_BUFFER, 0);

		/*
			Now disable all of the enabled attribute arrays that the PFX requested.
		*/
		for(unsigned int j = 0; j < aUniforms.GetSize(); ++j)
		{
			switch(aUniforms[j].nSemantic)
			{
			case ePVRTPFX_UsPOSITION:
			case ePVRTPFX_UsNORMAL:
			case ePVRTPFX_UsUV:
				{
					glDisableVertexAttribArray(aUniforms[j].nLocation);
				}
				break;
			}
		}
	}

	// Displays the demo name using the tools. For a detailed explanation, see the training course IntroducingPVRTools
	m_Print3D.DisplayDefaultTitle("IntroducingPFX", "", ePVRTPrint3DSDKLogo);
	m_Print3D.Flush();

	return true;
}
Пример #14
0
ShaderUniform& ShaderUniform::operator =(const glm::mat3 &m)
{
    glUniformMatrix3fv(m_location, 1, GL_FALSE /* do not transpose */, glm::value_ptr(m));
    return *this;
}
Пример #15
0
int contextDraw(context_t *ctx) {
  const char me[]="contextDraw";
  unsigned int gi;
  GLfloat modelMat[16];
/*
  if (ctx->buttonDown) {
    // When the mouse is down, use a velocity of zero 
    thetaPerSecU = 0;
    thetaPerSecV = 0;
    thetaPerSecN = 0;
  } else {
    // Otherwise, use the previous velocity 
    thetaPerSecU = ctx->thetaPerSecU;
    thetaPerSecV = ctx->thetaPerSecV;
    thetaPerSecN = ctx->thetaPerSecN;
  }


  gctx->angleU = (thetaPerSecU * dt) * 0.1;
  gctx->angleV = (thetaPerSecV * dt) * 0.1;
  gctx->angleN = (thetaPerSecN * dt) * 0.1;
  rotate_model_UV(gctx->angleU, -gctx->angleV);
  rotate_model_N(-gctx->angleN);
*/

  /* re-assert which program is being used (AntTweakBar uses its own) */
  glUseProgram(ctx->program); 

  /* background color; setting alpha=0 means that we'll see the
     background color in the render window, but upon doing
     "spotImageScreenshot(img, SPOT_TRUE)" (SPOT_TRUE for "withAlpha")
     we'll get a meaningful alpha channel, so that the image can
     recomposited with a different background, or used in programs
     (including web browsers) that respect the alpha channel */
  glClearColor(ctx->bgColor[0], ctx->bgColor[1], ctx->bgColor[2], 0.0f);
  /* Clear the window and the depth buffer */
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  
  /* The following will be useful when you want to use textures,
     especially two textures at once, here sampled in the fragment
     shader with "samplerA" and "samplerB".  There are some
     non-intuitive calls required to specify which texture data will
     be sampled by which sampler.  See OpenGL SuperBible (5th edition)
     pg 279.  Also, http://tinyurl.com/7bvnej3 is amusing and
     informative */

  // Sun
  glActiveTexture(GL_TEXTURE0);
  glBindTexture(GL_TEXTURE_2D, ctx->image[0]->textureId);
  glUniform1i(ctx->uniloc.sampler0, 0);

  // Mercury 
  glActiveTexture(GL_TEXTURE1);
  glBindTexture(GL_TEXTURE_2D, ctx->image[1]->textureId);
  glUniform1i(ctx->uniloc.sampler1, 1);

  // Venus
  glActiveTexture(GL_TEXTURE2);
  glBindTexture(GL_TEXTURE_2D, ctx->image[2]->textureId);
  glUniform1i(ctx->uniloc.sampler2, 2); 

  // Earth
  glActiveTexture(GL_TEXTURE3);
  glBindTexture(GL_TEXTURE_2D, ctx->image[3]->textureId);
  glUniform1i(ctx->uniloc.sampler3, 3); 

  // Mars
  glActiveTexture(GL_TEXTURE4);
  glBindTexture(GL_TEXTURE_2D, ctx->image[4]->textureId);
  glUniform1i(ctx->uniloc.sampler4, 4); 

  // Jupiter
  glActiveTexture(GL_TEXTURE5);
  glBindTexture(GL_TEXTURE_2D, ctx->image[5]->textureId);
  glUniform1i(ctx->uniloc.sampler5, 5); 

  // Saturn
  glActiveTexture(GL_TEXTURE6);
  glBindTexture(GL_TEXTURE_2D, ctx->image[6]->textureId);
  glUniform1i(ctx->uniloc.sampler6, 6); 

  // Uranus
  glActiveTexture(GL_TEXTURE7);
  glBindTexture(GL_TEXTURE_2D, ctx->image[7]->textureId);
  glUniform1i(ctx->uniloc.sampler7, 7); 

  // Neptune
  glActiveTexture(GL_TEXTURE8);
  glBindTexture(GL_TEXTURE_2D, ctx->image[8]->textureId);
  glUniform1i(ctx->uniloc.sampler8, 8); 

  // Pluto
  glActiveTexture(GL_TEXTURE9);
  glBindTexture(GL_TEXTURE_2D, ctx->image[9]->textureId);
  glUniform1i(ctx->uniloc.sampler9, 9); 

  // set time
  double toc = spotTime();
  if (ctx->ticDraw == -1)
    ctx->ticDraw = toc;
  double dt = toc - ctx->ticDraw;
  ctx->ticDraw = toc;

  if (!gctx->paused) {
    updateScene(gctx->time, dt);
  }

  // NOTE: we must normalize our UVN matrix
  norm_M4(gctx->camera.uvn);
	inverseUVN(gctx->camera.inverse_uvn, gctx->camera.uvn);

  // NOTE: update our unilocs
  glUniformMatrix4fv(ctx->uniloc.viewMatrix, 1, GL_FALSE, gctx->camera.uvn);
  glUniformMatrix4fv(ctx->uniloc.inverseViewMatrix, 1, GL_FALSE, gctx->camera.inverse_uvn);
  glUniformMatrix4fv(ctx->uniloc.projMatrix, 1, GL_FALSE, gctx->camera.proj);
  glUniform3fv(ctx->uniloc.lightDir, 1, ctx->lightDir);
  glUniform3fv(ctx->uniloc.lightColor, 1, ctx->lightColor);
  glUniform1i(ctx->uniloc.seamFix, ctx->seamFix);

  for (gi=0; gi<ctx->geomNum; gi++) {
    set_model_transform(modelMat, ctx->geom[gi]);
    glUniformMatrix4fv(ctx->uniloc.modelMatrix, 
                       1, GL_FALSE, modelMat);
    updateNormals(ctx->geom[gi]->normalMatrix, modelMat);
    glUniformMatrix3fv(ctx->uniloc.normalMatrix,
                       1, GL_FALSE, ctx->geom[gi]->normalMatrix);
    glUniform3fv(ctx->uniloc.objColor, 1, ctx->geom[gi]->objColor);
    glUniform1f(ctx->uniloc.Ka, ctx->geom[gi]->Ka);
    glUniform1f(ctx->uniloc.Kd, ctx->geom[gi]->Kd);
    glUniform1i(ctx->uniloc.gi, gi);
    spotGeomDraw(ctx->geom[gi]);
  }

/*
  // NOTE: update our geom-specific unilocs
  for (gi=sceneGeomOffset; gi<ctx->geomNum; gi++) {
    set_model_transform(modelMat, ctx->geom[gi]);
    // NOTE: we normalize the model matrix; while we may not need to, it is cheap to do so
    norm_M4(modelMat);
    glUniformMatrix4fv(ctx->uniloc.modelMatrix, 1, GL_FALSE, modelMat);
    // NOTE: we update normals in our `matrixFunctions.c' functions on a case-by-case basis
    updateNormals(gctx->geom[gi]->normalMatrix, modelMat);
    glUniformMatrix3fv(ctx->uniloc.normalMatrix, 1, GL_FALSE, ctx->geom[gi]->normalMatrix);
    //
    glUniform3fv(ctx->uniloc.objColor, 1, ctx->geom[gi]->objColor);
    glUniform1f(ctx->uniloc.Ka, ctx->geom[gi]->Ka);
    glUniform1f(ctx->uniloc.Kd, ctx->geom[gi]->Kd);
    glUniform1f(ctx->uniloc.Ks, ctx->geom[gi]->Ks);
    glUniform1i(ctx->uniloc.gi, gi);
    glUniform1f(ctx->uniloc.shexp, ctx->geom[gi]->shexp);
    spotGeomDraw(ctx->geom[gi]);
  }
  */
  /* These lines are also related to using textures.  We finish by
     leaving GL_TEXTURE0 as the active unit since AntTweakBar uses
     that, but doesn't seem to explicitly select it */
  glActiveTexture(GL_TEXTURE9);
  glBindTexture(GL_TEXTURE_2D, 9);
  glActiveTexture(GL_TEXTURE8);
  glBindTexture(GL_TEXTURE_2D, 8);
  glActiveTexture(GL_TEXTURE7);
  glBindTexture(GL_TEXTURE_2D, 7);
  glActiveTexture(GL_TEXTURE6);
  glBindTexture(GL_TEXTURE_2D, 6);
  glActiveTexture(GL_TEXTURE5);
  glBindTexture(GL_TEXTURE_2D, 5);
  glActiveTexture(GL_TEXTURE4);
  glBindTexture(GL_TEXTURE_2D, 4);
  glActiveTexture(GL_TEXTURE3);
  glBindTexture(GL_TEXTURE_2D, 3);
  glActiveTexture(GL_TEXTURE2);
  glBindTexture(GL_TEXTURE_2D, 2);
  glActiveTexture(GL_TEXTURE1); 
  glBindTexture(GL_TEXTURE_2D, 1);
  glActiveTexture(GL_TEXTURE0);
  glBindTexture(GL_TEXTURE_2D, 0);

  /* You are welcome to do error-checking with higher granularity than
     just once per render, in which case this error checking loop
     should be repackaged into its own function. */
  GLenum glerr = glGetError();
  if (glerr) {
    while (glerr) {
      spotErrorAdd("%s: OpenGL error %d (%s)", me, glerr, spotGLErrorString(glerr));
      glerr = glGetError();
    }
    return 1;
  }
  return 0;
}
Пример #16
0
void draw(struct hypnomix *hyp)
{
	float angle = hyp->var.smooth[0] * 2.0 * M_PI; // * hyp->pr.var[0];
	float translate = hyp->var.smooth[1] * hyp->pr.var[1];
	float scale = hyp->var.smooth[2] * hyp->pr.var[2];

	float facevtx[] = {
		-1.0, -1.0, 0.0,
		1.0, -1.0, 0.0,
		-1.0, 1.0, 0.0,
		1.0, 1.0, 0.0,
	};
	float facenrm[] = {
		0.0, 0.0, 1.0,
		0.0, 0.0, 1.0,
		0.0, 0.0, 1.0,
		0.0, 0.0, 1.0
	};
	float faceclr[] = {
		0.0, 0.0, 1.0, 1.0,
		0.0, 0.0, 1.0, 1.0,
		0.0, 0.0, 1.0, 1.0,
		0.0, 0.0, 1.0, 1.0 
	}; 
	unsigned int faceidx[] = {
		0, 1, 2,
		2, 1, 3
	};
	skyboxDraw(hyp, 0.0, angle, 0.0);

	transformIdentity(&hyp->tr);
//	transformModelScale(&hyp->tr, scale, scale, scale);
	transformModelRotate(&hyp->tr, 0.0, angle, 0.0); 
//	transformViewRotate(&hyp->tr, 0.0, angle, 0.0);
	transformViewTranslate(&hyp->tr, 0.0, 0.0, -4.0);
	transformMVP(&hyp->tr);



	glUseProgram(hyp->pg.id);
	glEnableVertexAttribArray(hyp->pg.pos);
	glEnableVertexAttribArray(hyp->pg.clr);
	glEnableVertexAttribArray(hyp->pg.nrm);

	glUniformMatrix4fv(hyp->pg.mvp, 1, GL_FALSE, hyp->tr.mvp);
	glUniformMatrix3fv(hyp->pg.mnormal, 1, GL_FALSE, hyp->tr.mnormal);

//	transformMVCoordinates(&hyp->tr, &(hyp->lights.dir[0]), lightdir[0]);
//lightdir[0][0] = 0.0;
//lightdir[0][1] = 0.0;
//lightdir[0][2] = 1.0;
//	glUniform3fv(hyp->pg.lightdir, hyp->lights.nb, lightdir[0]);
//	transformMVCoordinates(&hyp->tr, &(hyp->lights.pos[0]), lightpos[0]);
//	glUniform3fv(hyp->pg.lightpos, hyp->lights.nb, lightpos[0]);

vec4 lightdir; 
vec4 tmp;
tmp[0] = hyp->lights.dir[0][0];
tmp[1] = hyp->lights.dir[0][1];
tmp[2] = hyp->lights.dir[0][2];
tmp[3] = 0.0;
	mat4Vec4Mul(hyp->tr.view, tmp, lightdir);
	vec4Normalize(lightdir, lightdir);

/*fprintf(stderr, "LIGHTDIR=%f,%f,%f,%f\n", lightdir[0], lightdir[1], lightdir[2], lightdir[3]); */
glUniform3fv(hyp->pg.lightdir, hyp->lights.nb, lightdir);
//glUniform3fv(hyp->pg.lightpos, hyp->lights.nb, hyp->lights.pos);
/*
	glVertexAttribPointer(hyp->pg.pos, 3, GL_FLOAT, GL_FALSE, 0, vtx);
	glVertexAttribPointer(hyp->pg.nrm, 3, GL_FLOAT, GL_FALSE, 0, nrm);
	glVertexAttribPointer(hyp->pg.clr, 4, GL_FLOAT, GL_FALSE, 0, clr);
*/
//glEnable(GL_CULL_FACE);
//glCullFace(GL_BACK);

glVertexAttribPointer(hyp->pg.pos, 3, GL_FLOAT, GL_FALSE, 0, facevtx);
glVertexAttribPointer(hyp->pg.nrm, 3, GL_FLOAT, GL_FALSE, 0, facenrm);
glVertexAttribPointer(hyp->pg.clr, 4, GL_FLOAT, GL_FALSE, 0, faceclr);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, faceidx);


//	glDrawElements(GL_TRIANGLES, 12, GL_UNSIGNED_INT, idx);
//glDisable(GL_CULL_FACE);


/* show normals */

float nrmlines[4*6];
float x, y, z;
int i;

for(i = 0; i < 4; i++) {
	x = facevtx[i*3];
	y = facevtx[i*3+1];
	z = facevtx[i*3+2];

	nrmlines[i*6] = x;
	nrmlines[i*6+1] = y;
	nrmlines[i*6+2] = z;

	nrmlines[i*6+3] = x + facenrm[i*3] * 0.4;
	nrmlines[i*6+4] = y + facenrm[i*3+1] * 0.4;
	nrmlines[i*6+5] = z + facenrm[i*3+2] * 0.4;
}
glVertexAttribPointer(hyp->pg.pos, 3, GL_FLOAT, GL_FALSE, 0, nrmlines);
glDrawArrays(GL_LINES, 0, 8); 
/* end show normals */

	glDisableVertexAttribArray(hyp->pg.nrm);
	glDisableVertexAttribArray(hyp->pg.clr);
	glDisableVertexAttribArray(hyp->pg.pos);
}
Пример #17
0
void RenderScene(void) {
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);


	glUniform3fv(shaderMaterialAmbientLocation, 1, ambientColor);
	glUniform3fv(shaderMaterialDiffuseLocation, 1, diffuseColor);
	glUniform3fv(shaderMaterialSpecularLocation, 1, specularColor);
	glUniform1f(shaderMaterialSpecularExponentLocation, specularExponent);
	
	
	glUniform3fv(shaderPositionLocation, 1, position);
	glUniform3fv(shaderColorLocation, 1, color);
	glUniform1f(shaderAngleLocation, angle);
	glUniform1f(shaderAttenuation0Location, attenuation0);
	glUniform1f(shaderAttenuation1Location, attenuation1);
	glUniform1f(shaderAttenuation2Location, attenuation2);


	GLMatrixStack modelView;
	GLMatrixStack projection;
	GLGeometryTransform geometryPipeline;
	geometryPipeline.SetMatrixStacks(modelView,projection);

	projection.LoadMatrix(frustum.GetProjectionMatrix());
	modelView.PushMatrix();
	M3DMatrix44f mCamera;
	cameraFrame.GetCameraMatrix(mCamera);
	modelView.LoadMatrix(mCamera);
	modelView.PushMatrix();

	
	glUniformMatrix4fv(MVPMatrixLocation,1,GL_FALSE,geometryPipeline.GetModelViewProjectionMatrix());
	rysujSiatke();

	modelView.PushMatrix();
	modelView.Translate(0.0f,0.0f,-1.f);
	glUniformMatrix4fv(MVMatrixLocation,1,GL_FALSE,geometryPipeline.GetModelViewMatrix());
	glUniformMatrix3fv(MNMatrixLocation,1,GL_FALSE,geometryPipeline.GetNormalMatrix());
	glUniformMatrix4fv(MVPMatrixLocation,1,GL_FALSE,geometryPipeline.GetModelViewProjectionMatrix());
	rysujTrojkat();
	modelView.PopMatrix();


	modelView.PushMatrix();
	modelView.Translate(0.0f,4.0f,0.f);
	glUniformMatrix4fv(MVMatrixLocation,1,GL_FALSE,geometryPipeline.GetModelViewMatrix());
	glUniformMatrix3fv(MNMatrixLocation,1,GL_FALSE,geometryPipeline.GetNormalMatrix());
	glUniformMatrix4fv(MVPMatrixLocation,1,GL_FALSE,geometryPipeline.GetModelViewProjectionMatrix());
	rysujTrojkat();
	modelView.PopMatrix();


	modelView.PushMatrix();
	modelView.Translate(3.0f,-3.0f,0.f);
	modelView.Scale(2.0f,2.0f,2.f);
	modelView.Rotate(45,0,0,1);
	glUniformMatrix4fv(MVMatrixLocation,1,GL_FALSE,geometryPipeline.GetModelViewMatrix());
	glUniformMatrix3fv(MNMatrixLocation,1,GL_FALSE,geometryPipeline.GetNormalMatrix());
	glUniformMatrix4fv(MVPMatrixLocation,1,GL_FALSE,geometryPipeline.GetModelViewProjectionMatrix());
	rysujTrojkat();
	modelView.PopMatrix();


	modelView.PushMatrix();
	modelView.Translate(3.0f,3.0f,0.f);
	glUniformMatrix4fv(MVMatrixLocation,1,GL_FALSE,geometryPipeline.GetModelViewMatrix());
	glUniformMatrix3fv(MNMatrixLocation,1,GL_FALSE,geometryPipeline.GetNormalMatrix());
	glUniformMatrix4fv(MVPMatrixLocation,1,GL_FALSE,geometryPipeline.GetModelViewProjectionMatrix());
	drawTriangles(20, ico_vertices,ico_faces);
	modelView.PopMatrix();

	modelView.PushMatrix();
	modelView.Translate(0.0f,0.0f,7.f);
	modelView.Rotate(90+rotAngle,1,1,1);
	modelView.Scale(2.0f,2.5f,2.5f);
	glUniformMatrix4fv(MVMatrixLocation,1,GL_FALSE,geometryPipeline.GetModelViewMatrix());
	glUniformMatrix3fv(MNMatrixLocation,1,GL_FALSE,geometryPipeline.GetNormalMatrix());
	glUniformMatrix4fv(MVPMatrixLocation,1,GL_FALSE,geometryPipeline.GetModelViewProjectionMatrix());
	drawTriangles(20, ico_vertices,ico_faces);
	modelView.PopMatrix();




	modelView.PushMatrix();
	modelView.Translate(-4.0f,0.0f,4.f);
	modelView.Scale(2.0f,2.0f,2.0f);

	glUniformMatrix4fv(MVMatrixLocation,1,GL_FALSE,geometryPipeline.GetModelViewMatrix());
	glUniformMatrix3fv(MNMatrixLocation,1,GL_FALSE,geometryPipeline.GetNormalMatrix());
	glUniformMatrix4fv(MVPMatrixLocation,1,GL_FALSE,geometryPipeline.GetModelViewProjectionMatrix());
	glDrawElements(GL_TRIANGLES,3*n_faces,GL_UNSIGNED_INT,0);

	modelView.PopMatrix();


    // Perform the buffer swap to display back buffer
    glutSwapBuffers();
	rotAngle+=5.f;
	if(!stopRotate){
	M3DVector3f at={0,0,0};
	M3DVector3f up={0,0,1};
	M3DVector3f eye;
	float angle = timer.GetElapsedSeconds()*3.14159f /3.f;
	eye[0]=16.f*cos(angle);
	eye[1]=40.0f*sin(angle);
	eye[2]=20.0f; 
	LookAt(cameraFrame,eye,at,up);
	}
glutPostRedisplay();
}
Пример #18
0
void ShaderNode::updateUniforms( QList<ShaderBindData> &Bindings, qint64 pTimeStamp )
{
	bool		NumberOK;

	for( ShaderUniformMap::iterator it = mShaderUniformTypes.begin() ; it != mShaderUniformTypes.end() ; it++ )
	{
		ShaderUniformData				&UniformData = it.value();
		QSharedPointer<InterfacePin>	PIN = mNode->findPinByName( it.key() );

		if( PIN == 0 )
		{
			continue;
		}

		if( !PIN->isConnected() )
		{
			continue;
		}

		QSharedPointer<InterfacePinControl>		PinControl = PIN->connectedPin()->control();

		if( PinControl == 0 )
		{
			continue;
		}

		if( UniformData.mSampler && UniformData.mSize == 1 )
		{
			bindTexture( Bindings, PinControl, UniformData );

			continue;
		}

		//		if( mLastShaderLoad < pTimeStamp )//&& !PIN->isUpdated( pTimeStamp ) )
		//		{
		//			if( PIN->controlUuid() == PID_TRIGGER )
		//			{
		//				switch( UniformData.mType )
		//				{
		//					case GL_BOOL:
		//						glUniform1f( UniformData.mLocation, false );
		//						break;
		//				}
		//			}

		//			continue;
		//		}

		if( true )
		{
			InterfaceVariant		*PinVariant = qobject_cast<InterfaceVariant *>( PinControl->object() );

			if( PinVariant != 0 )
			{
				switch( UniformData.mType )
				{
					case GL_BOOL:
						{
							GLboolean		NewVal = PinVariant->variant().toBool();

							glUniform1ui( UniformData.mLocation, NewVal );
						}
						break;

					case GL_INT:
						{
							GLint		NewVal = PinVariant->variant().toInt( &NumberOK );

							if( NumberOK )
							{
								glUniform1i( UniformData.mLocation, NewVal );
							}
						}
						break;

					case GL_FLOAT:
						{
							GLfloat		NewVal = PinVariant->variant().toFloat( &NumberOK );

							if( NumberOK )
							{
								glUniform1f( UniformData.mLocation, NewVal );
							}
						}
						break;

					case GL_FLOAT_VEC2:
						{
							QVector2D		Vec2 = PinVariant->variant().value<QVector2D>();

							glUniform2f( UniformData.mLocation, Vec2.x(), Vec2.y() );
						}
						break;

					case GL_FLOAT_VEC3:
						{
							QVector3D		Vec3 = PinVariant->variant().value<QVector3D>();

							glUniform3f( UniformData.mLocation, Vec3.x(), Vec3.y(), Vec3.z() );
						}
						break;

					case GL_FLOAT_VEC4:
						{
							QVector4D		Vec4 = PinVariant->variant().value<QVector4D>();

							glUniform4f( UniformData.mLocation, Vec4.x(), Vec4.y(), Vec4.z(), Vec4.w() );
						}
						break;

					case GL_FLOAT_MAT2:
						{
							QMatrix4x4		Mat4 = PinVariant->variant().value<QMatrix4x4>();
							QMatrix2x2		Mat2 = Mat4.toGenericMatrix<2,2>();

							glUniformMatrix2fv( UniformData.mLocation, 1, GL_FALSE, Mat2.constData() );
						}
						break;

					case GL_FLOAT_MAT3:
						{
							QMatrix4x4		Mat4 = PinVariant->variant().value<QMatrix4x4>();
							QMatrix3x3		Mat3 = Mat4.toGenericMatrix<3,3>();

							//qDebug() << Mat4;
							//qDebug() << Mat3;

							glUniformMatrix3fv( UniformData.mLocation, 1, GL_FALSE, Mat3.constData() );
						}
						break;

					case GL_FLOAT_MAT4:
						{
							QMatrix4x4		NewVal = PinVariant->variant().value<QMatrix4x4>();

							glUniformMatrix4fv( UniformData.mLocation, 1, GL_FALSE, NewVal.constData() );
						}
						break;
				}

				OPENGL_PLUGIN_DEBUG;

				continue;
			}
		}

		if( true )
		{
			InterfaceColour		*PinColour = qobject_cast<InterfaceColour *>( PinControl->object() );

			if( PinColour != 0 )
			{
				switch( UniformData.mType )
				{
					case GL_FLOAT_VEC3:
						glUniform3f( UniformData.mLocation, PinColour->colour().redF(), PinColour->colour().greenF(), PinColour->colour().blueF() );
						break;

					case GL_FLOAT_VEC4:
						glUniform4f( UniformData.mLocation, PinColour->colour().redF(), PinColour->colour().greenF(), PinColour->colour().blueF(), PinColour->colour().alphaF() );
						break;
				}

				OPENGL_PLUGIN_DEBUG;

				continue;
			}
		}

		if( true )
		{
			if( PIN->controlUuid() == PID_TRIGGER )
			{
				switch( UniformData.mType )
				{
					case GL_BOOL:
						glUniform1f( UniformData.mLocation, true );
						break;
				}

				OPENGL_PLUGIN_DEBUG;

				continue;
			}
		}
	}
}
Пример #19
0
/*!****************************************************************************
 @Function		RenderScene
 @Return		bool		true if no error occured
 @Description	Main rendering loop function of the program. The shell will
				call this function every frame.
				eglSwapBuffers() will be performed by PVRShell automatically.
				PVRShell will also manage important OS events.
				Will also manage relevent OS events. The user has access to
				these events through an abstraction layer provided by PVRShell.
******************************************************************************/
bool OGLES2LevelOfDetail::RenderScene()
{
	// Clear the color and depth buffer
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	// Use shader program
	glUseProgram(m_ShaderProgram.uiId);

	// Bind textures
	glActiveTexture(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_2D, m_uiReflectTex);
	glActiveTexture(GL_TEXTURE1);
	glBindTexture(GL_TEXTURE_2D, m_uiNormalTex);

	// Rotate and Translate the model matrix
	PVRTMat4 mModel, mRotY, mTrans;
	float fDistance = 1400.0f * cos(m_fPositionZ) - 1350.0f;
	
	mTrans = PVRTMat4::Translation(0.0, 0.0, fDistance);
	mRotY = PVRTMat4::RotationY(m_fAngleY);
	mModel = mTrans * mRotY;

	m_fAngleY += PVRT_PI / 210;
	m_fPositionZ += 2 * PVRT_PI * 0.0008f;

	// Set model view projection matrix
	PVRTMat4 mModelView, mMVP;
	mModelView = m_mView * mModel;
	mMVP = m_mProjection * mModelView;
	glUniformMatrix4fv(m_ShaderProgram.auiLoc[eMVPMatrix], 1, GL_FALSE, mMVP.ptr());

	// Set model matrix
	PVRTMat3 Model3x3 = PVRTMat3(mModel);

	glUniformMatrix3fv(m_ShaderProgram.auiLoc[eModelWorld], 1, GL_FALSE, Model3x3.ptr());

	// Set eye position in model space
	PVRTVec4 vEyePosModel;
	vEyePosModel = mModelView.inverse() * PVRTVec4(0, 0, 0, 1);

	glUniform3fv(m_ShaderProgram.auiLoc[eEyePosModel], 1, &vEyePosModel.x);

	// Calculate the square of the pixel area that the mesh takes up on screen
	// This is done by projecting the vertices of the bounding box to screen space
	// then taking the axis aligned 2D bounding box of the projected vertices.
	// This is a very conservative estimate
	float fMinX, fMaxX, fMinY, fMaxY, fX, fY;
	ProjectVertex(m_avBoundingBox[0], mMVP, fX, fY);
	fMinX = fMaxX = fX;
	fMinY = fMaxY = fY;

	for (int i = 1; i < 8; ++i)
	{
		ProjectVertex(m_avBoundingBox[i], mMVP, fX, fY);
		fMinX = PVRT_MIN(fMinX, fX);
		fMinY = PVRT_MIN(fMinY, fY);
		fMaxX = PVRT_MAX(fMaxX, fX);
		fMaxY = PVRT_MAX(fMaxY, fY);
	}

	// Choose high detail if the mesh bounding box covers more than 2% of the screen
	m_bHighDetail = ((fMaxX - fMinX) * (fMaxY - fMinY) > 0.02);
	glUniform1i(m_ShaderProgram.auiLoc[eHighDetail], m_bHighDetail);

	/*
		Now that the uniforms are set, call another function to actually draw the mesh.
	*/
	DrawMesh(m_bHighDetail ? 0 : 1);

	// Displays the demo name using the tools. For a detailed explanation, see the training course IntroducingPVRTools
	m_Print3D.DisplayDefaultTitle("Level of detail", (m_bHighDetail) ? "Detail: high" : "Detail: low", ePVRTPrint3DLogoIMG);
	m_Print3D.Flush();
	return true;
}
Пример #20
0
void ShaderProgram::setUniformMatrix3f(const std::string& _name, const float* _value, bool _transpose) {
    use();
    GLint location = getUniformLocation(_name);
    glUniformMatrix3fv(location, 1, _transpose, _value);
}
Пример #21
0
int main() {
  // Initialize GLFW and set some hints that will create an OpenGL 3.3 context
  // using core profile.
  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);
  glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

  // Create a fixed 800x600 window that is not resizable.
  GLFWwindow* window = glfwCreateWindow(kWindowWidth, kWindowHeight, "LearnGL", nullptr, nullptr);
  if (window == nullptr) {
    std::cerr << "Failed to created GLFW window" << std::endl;
    glfwTerminate();
    return 1;
  }

  // Create an OpenGL context and pass callbacks to GLFW.
  glfwMakeContextCurrent(window);
  glfwSetKeyCallback(window, keyCallback);
  glfwSetCursorPosCallback(window, mouseCallback);
  glfwSetScrollCallback(window, scrollCallback);

  // Lock the mouse in the window.
  glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);

  glewExperimental = GL_TRUE;
  if (glewInit() != GLEW_OK) {
    std::cerr << "Failed to initialize GLEW" << std::endl;
    glfwTerminate();
    return 1;
  }

  // Create a viewport the same size as the window. glfwGetFramebufferSize is
  // used rather than the size constants since some windowing systems have a
  // discrepancy between window size and framebuffer size
  // (e.g HiDPi screen coordinates),
  int fbWidth, fbHeight;
  glfwGetFramebufferSize(window, &fbWidth, &fbHeight);
  glViewport(0, 0, fbWidth, fbHeight);

  // Enable use of the depth buffer since we're working on 3D and want to
  // prevent overlapping polygon artifacts.
  glEnable(GL_DEPTH_TEST);

  // Read and compile the vertex and fragment shaders using
  // the shader helper class.
  Shader shader("glsl/vertex.glsl", "glsl/fragment.glsl", "glsl/geometry.glsl");
  Shader lampShader("glsl/lampvertex.glsl", "glsl/lampfragment.glsl");
  Shader postShader("glsl/post_vert.glsl", "glsl/post_frag.glsl");
  Shader gsShader("glsl/gs_vert.glsl", "glsl/gs_frag.glsl", "glsl/gs_geo.glsl");

  GLuint containerTexture = loadTexture("assets/container2.png");
  GLuint containerSpecular = loadTexture("assets/container2_specular.png");
  GLuint containerEmission = loadTexture("assets/matrix.jpg");

  // Create and bind a framebuffer.
  GLuint FBO;
  glGenFramebuffers(1, &FBO);
  glBindFramebuffer(GL_FRAMEBUFFER, FBO);

  // Create an empty texture to be attached to the framebuffer.
  // Give a null pointer to glTexImage2D since we want an empty texture.
  GLuint frameColorBuffer;
  glGenTextures(1, &frameColorBuffer);
  glBindTexture(GL_TEXTURE_2D, frameColorBuffer);
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, fbWidth, fbHeight, 0, GL_RGB,
      GL_UNSIGNED_BYTE, nullptr);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  glBindTexture(GL_TEXTURE_2D, 0);

  // Attach the texture to the framebuffer.
  glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
      frameColorBuffer, 0);

  // Create a renderbuffer to hold our depth and stencil buffers with a size
  // of the window's framebuffer size.
  GLuint RBO;
  glGenRenderbuffers(1, &RBO);
  glBindRenderbuffer(GL_RENDERBUFFER, RBO);
  glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8,
      fbWidth, fbHeight);
  glBindRenderbuffer(GL_RENDERBUFFER, 0);

  // Attach the render buffer (provides depth and stencil) to the framebuffer.
  glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT,
      GL_RENDERBUFFER, RBO);

  // Panic if the framebuffer is somehow incomplete at this stage. This should
  // never happen if we attached the texture but it's good practice to check.
  if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
    std::cerr << "ERROR: Framebuffer is not complete!" << std::endl;
    glfwTerminate();
    return 1;
  }

  // Unbind the framebuffer since we want the main scene to be drawn
  // to be drawn to the main window.
  glBindFramebuffer(GL_FRAMEBUFFER, 0);

  // Container mesh data.
  GLfloat vertices[] = {
    // Vertices          // Normals           // UVs
    -0.5f, -0.5f, -0.5f,  0.0f,  0.0f, -1.0f,  0.0f, 0.0f,
     0.5f, -0.5f, -0.5f,  0.0f,  0.0f, -1.0f,  1.0f, 0.0f,
     0.5f,  0.5f, -0.5f,  0.0f,  0.0f, -1.0f,  1.0f, 1.0f,
     0.5f,  0.5f, -0.5f,  0.0f,  0.0f, -1.0f,  1.0f, 1.0f,
    -0.5f,  0.5f, -0.5f,  0.0f,  0.0f, -1.0f,  0.0f, 1.0f,
    -0.5f, -0.5f, -0.5f,  0.0f,  0.0f, -1.0f,  0.0f, 0.0f,

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

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

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

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

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

  // Points for the geometry shader tutorial.
  GLfloat points[] = {
    -0.5f,  0.5f, 1.0f, 0.0f, 0.0f, // Top-left
     0.5f,  0.5f, 0.0f, 1.0f, 0.0f, // Top-right
     0.5f, -0.5f, 0.0f, 0.0f, 1.0f, // Bottom-right
    -0.5f, -0.5f, 1.0f, 1.0f, 0.0f  // Bottom-left
  };

  // Positions all containers
  glm::vec3 cubePositions[] = {
    glm::vec3( 0.0f,  0.0f,  0.0f),
    glm::vec3( 2.0f,  5.0f, -15.0f),
    glm::vec3(-1.5f, -2.2f, -2.5f),
    glm::vec3(-3.8f, -2.0f, -12.3f),
    glm::vec3( 2.4f, -0.4f, -3.5f),
    glm::vec3(-1.7f,  3.0f, -7.5f),
    glm::vec3( 1.3f, -2.0f, -2.5f),
    glm::vec3( 1.5f,  2.0f, -2.5f),
    glm::vec3( 1.5f,  0.2f, -1.5f),
    glm::vec3(-1.3f,  1.0f, -1.5f)
  };

  // Create a VBO to store the vertex data, an EBO to store indice data, and
  // create a VAO to retain our vertex attribute pointers.
  GLuint VBO, VAO;
  glGenVertexArrays(1, &VAO);
  glGenBuffers(1, &VBO);

  // Fill the VBO and set vertex attributes.
  glBindVertexArray(VAO);
  glBindBuffer(GL_ARRAY_BUFFER, VBO);
  glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
  glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)0);
  glEnableVertexAttribArray(0);
  glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
  glEnableVertexAttribArray(1);
  glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(6 * sizeof(GLfloat)));
  glEnableVertexAttribArray(2);
  glBindVertexArray(0);

  // Create a lamp box thing using the existing container VBO.
  GLuint lightVAO;
  glGenVertexArrays(1, &lightVAO);

  // Use the container's VBO and set vertex attributes.
  glBindVertexArray(lightVAO);
  glBindBuffer(GL_ARRAY_BUFFER, VBO);
  glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)0);
  glEnableVertexAttribArray(0);
  glBindVertexArray(0);

  // Vertex attributes for the frame quad in NDC.
  GLfloat frameVertices[] = {
    // Positions  // UVs
    -1.0f,  1.0f,  0.0f, 1.0f,
    -1.0f, -1.0f,  0.0f, 0.0f,
     1.0f, -1.0f,  1.0f, 0.0f,

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

  // Create a VBO and VAO for the post-processing step.
  GLuint frameVBO, frameVAO;
  glGenVertexArrays(1, &frameVAO);
  glGenBuffers(1, &frameVBO);

  glBindVertexArray(frameVAO);
  glBindBuffer(GL_ARRAY_BUFFER, frameVBO);
  glBufferData(GL_ARRAY_BUFFER, sizeof(frameVertices), frameVertices,
      GL_STATIC_DRAW);
  glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat),
      (GLvoid*)0);
  glEnableVertexAttribArray(0);
  glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat),
      (GLvoid*)(2 * sizeof(GLfloat)));
  glEnableVertexAttribArray(1);
  glBindVertexArray(0);

  // Create a VBO and VAO for the geometry shader test. The VBO will contain
  // only the position.
  GLuint pointsVBO, pointsVAO;
  glGenVertexArrays(1, &pointsVAO);
  glGenBuffers(1, &pointsVBO);

  glBindVertexArray(pointsVAO);
  glBindBuffer(GL_ARRAY_BUFFER, pointsVBO);
  glBufferData(GL_ARRAY_BUFFER, sizeof(points), points, GL_STATIC_DRAW);
  glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat),
      (GLvoid*)0);
  glEnableVertexAttribArray(0);
  glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat),
      (GLvoid*)(2 * sizeof(GLfloat)));
  glEnableVertexAttribArray(1);
  glBindVertexArray(0);

  // Create a perspective camera to fit the viewport.
  screenWidth = (GLfloat)fbWidth;
  screenHeight = (GLfloat)fbHeight;
  camera = PerspectiveCamera(
    glm::vec3(0.0f, 0.0f, 3.0f),
    glm::vec3(0.0f, glm::radians(-90.0f), 0.0f),
    glm::radians(45.0f),
    screenWidth / screenHeight,
    0.1f,
    100.0f
  );

  GLfloat delta = 0.0f;
  GLfloat lastFrame = 0.0f;

  // Light information.
  const glm::vec3 directionalLightDir(0.0f, 1.0f, 0.0f);
  const glm::vec3 pointLightPositions[] = {
    glm::vec3( 0.7f,  0.2f,  2.0f),
    glm::vec3( 2.3f, -3.3f, -4.0f),
    glm::vec3(-4.0f,  2.0f, -12.0f),
    glm::vec3( 0.0f,  0.0f, -3.0f)
  };

  // Render loop.
  while (!glfwWindowShouldClose(window)) {
    GLfloat currentFrame = glfwGetTime();
    delta = currentFrame - lastFrame;
    lastFrame = currentFrame;

    // Check and call events.
    glfwPollEvents();
    move(delta);

    // Bind the off screen framebuffer (for post-processing) and clear the
    // screen to a nice blue color.
    glBindFramebuffer(GL_FRAMEBUFFER, FBO);
    glClearColor(0.1f, 0.15f, 0.15f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glEnable(GL_DEPTH_TEST);

    const GLfloat limitTime = 1.0f;
    fovTime += delta;
    if (fovTime > limitTime) {
      fovTime = limitTime;
    }

    // Update the perspective to account for changes in fov.
    camera.fov = easeOutQuart(fovTime, startFov, (startFov - targetFov) * -1, limitTime);
    camera.update();

    // Bind the VAO and shader.
    glBindVertexArray(VAO);
    shader.use();

    // Pass the view and projection matrices from the camera.
    GLuint viewMatrix = glGetUniformLocation(shader.program, "view");
    glUniformMatrix4fv(viewMatrix, 1, GL_FALSE, glm::value_ptr(camera.view));
    GLuint projectionMatrix = glGetUniformLocation(shader.program, "projection");
    glUniformMatrix4fv(projectionMatrix, 1, GL_FALSE, glm::value_ptr(camera.projection));

    // Generate light colors.
    glm::vec3 lightColor(1.0f, 1.0f, 1.0f);

    // Directional light
    glUniform3f(glGetUniformLocation(shader.program, "dirLight.direction"), -0.2f, -1.0f, -0.3f);
    glUniform3f(glGetUniformLocation(shader.program, "dirLight.ambient"), 0.05f, 0.05f, 0.05f);
    glUniform3f(glGetUniformLocation(shader.program, "dirLight.diffuse"), 0.4f, 0.4f, 0.4f);
    glUniform3f(glGetUniformLocation(shader.program, "dirLight.specular"), 0.5f, 0.5f, 0.5f);

    // Point light 1
    glUniform3f(glGetUniformLocation(shader.program, "pointLights[0].position"), pointLightPositions[0].x, pointLightPositions[0].y, pointLightPositions[0].z);
    glUniform3f(glGetUniformLocation(shader.program, "pointLights[0].ambient"), 0.05f, 0.05f, 0.05f);
    glUniform3f(glGetUniformLocation(shader.program, "pointLights[0].diffuse"), 1.0f, 0.0f, 0.0f);
    glUniform3f(glGetUniformLocation(shader.program, "pointLights[0].specular"), 1.0f, 1.0f, 1.0f);
    glUniform1f(glGetUniformLocation(shader.program, "pointLights[0].constant"), 1.0f);
    glUniform1f(glGetUniformLocation(shader.program, "pointLights[0].linear"), 0.09);
    glUniform1f(glGetUniformLocation(shader.program, "pointLights[0].quadratic"), 0.032);

    // Point light 2
    glUniform3f(glGetUniformLocation(shader.program, "pointLights[1].position"), pointLightPositions[1].x, pointLightPositions[1].y, pointLightPositions[1].z);
    glUniform3f(glGetUniformLocation(shader.program, "pointLights[1].ambient"), 0.05f, 0.05f, 0.05f);
    glUniform3f(glGetUniformLocation(shader.program, "pointLights[1].diffuse"), 0.0f, 1.0f, 0.0f);
    glUniform3f(glGetUniformLocation(shader.program, "pointLights[1].specular"), 1.0f, 1.0f, 1.0f);
    glUniform1f(glGetUniformLocation(shader.program, "pointLights[1].constant"), 1.0f);
    glUniform1f(glGetUniformLocation(shader.program, "pointLights[1].linear"), 0.09);
    glUniform1f(glGetUniformLocation(shader.program, "pointLights[1].quadratic"), 0.032);

    // Point light 3
    glUniform3f(glGetUniformLocation(shader.program, "pointLights[2].position"), pointLightPositions[2].x, pointLightPositions[2].y, pointLightPositions[2].z);
    glUniform3f(glGetUniformLocation(shader.program, "pointLights[2].ambient"), 0.05f, 0.05f, 0.05f);
    glUniform3f(glGetUniformLocation(shader.program, "pointLights[2].diffuse"), 0.0f, 0.0f, 1.0f);
    glUniform3f(glGetUniformLocation(shader.program, "pointLights[2].specular"), 1.0f, 1.0f, 1.0f);
    glUniform1f(glGetUniformLocation(shader.program, "pointLights[2].constant"), 1.0f);
    glUniform1f(glGetUniformLocation(shader.program, "pointLights[2].linear"), 0.09);
    glUniform1f(glGetUniformLocation(shader.program, "pointLights[2].quadratic"), 0.032);

    // Point light 4
    glUniform3f(glGetUniformLocation(shader.program, "pointLights[3].position"), pointLightPositions[3].x, pointLightPositions[3].y, pointLightPositions[3].z);
    glUniform3f(glGetUniformLocation(shader.program, "pointLights[3].ambient"), 0.05f, 0.05f, 0.05f);
    glUniform3f(glGetUniformLocation(shader.program, "pointLights[3].diffuse"), 0.8f, 0.8f, 0.8f);
    glUniform3f(glGetUniformLocation(shader.program, "pointLights[3].specular"), 1.0f, 1.0f, 1.0f);
    glUniform1f(glGetUniformLocation(shader.program, "pointLights[3].constant"), 1.0f);
    glUniform1f(glGetUniformLocation(shader.program, "pointLights[3].linear"), 0.09);
    glUniform1f(glGetUniformLocation(shader.program, "pointLights[3].quadratic"), 0.032);

    // Sport light 1
    glUniform3f(glGetUniformLocation(shader.program, "spotLights[0].position"), camera.position.x, camera.position.y, camera.position.z);
    glUniform3f(glGetUniformLocation(shader.program, "spotLights[0].direction"), camera.front.x, camera.front.y, camera.front.z);
    glUniform3f(glGetUniformLocation(shader.program, "spotLights[0].ambient"), 0.0f, 0.0f, 0.0f);
    glUniform3f(glGetUniformLocation(shader.program, "spotLights[0].diffuse"), 1.0f, 1.0f, 1.0f);
    glUniform3f(glGetUniformLocation(shader.program, "spotLights[0].specular"), 1.0f, 1.0f, 1.0f);
    glUniform1f(glGetUniformLocation(shader.program, "spotLights[0].constant"), 1.0f);
    glUniform1f(glGetUniformLocation(shader.program, "spotLights[0].linear"), 0.09);
    glUniform1f(glGetUniformLocation(shader.program, "spotLights[0].quadratic"), 0.032);
    glUniform1f(glGetUniformLocation(shader.program, "spotLights[0].cutoff"), glm::cos(glm::radians(12.5f)));
    glUniform1f(glGetUniformLocation(shader.program, "spotLights[0].outerCutoff"), glm::cos(glm::radians(15.5f)));

    // Pass material values.
    GLuint materialShininess = glGetUniformLocation(shader.program, "material.shininess");
    GLuint materialDiffuse   = glGetUniformLocation(shader.program, "material.diffuse");
    GLuint materialSpecular  = glGetUniformLocation(shader.program, "material.specular");
    GLuint materialEmission  = glGetUniformLocation(shader.program, "material.emission");
    glUniform1f(materialShininess, 64.0f);
    glUniform1i(materialDiffuse, 0);
    glUniform1i(materialSpecular, 1);
    glUniform1i(materialEmission, 2);

    // Misc values.
    GLuint viewPos = glGetUniformLocation(shader.program, "viewPos");
    glUniform3f(viewPos, camera.position.x, camera.position.y, camera.position.z);
    GLuint time = glGetUniformLocation(shader.program, "time");
    glUniform1f(time, glfwGetTime());

    // Bind the textures.
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, containerTexture);
    glActiveTexture(GL_TEXTURE1);
    glBindTexture(GL_TEXTURE_2D, containerSpecular);
    glActiveTexture(GL_TEXTURE2);
    glBindTexture(GL_TEXTURE_2D, containerEmission);

    // Draw multiple containers!
    GLuint modelMatrix = glGetUniformLocation(shader.program, "model");
    GLuint normalMatrix = glGetUniformLocation(shader.program, "normalMatrix");
    for (GLuint i = 0; i < 10; i++) {
      // Apply world transformations.
      model = glm::mat4();
      model = glm::translate(model, cubePositions[i]);
      model = glm::rotate(model, i * 20.0f, glm::vec3(1.0f, 0.3f, 0.5f));
      glUniformMatrix4fv(modelMatrix, 1, GL_FALSE, glm::value_ptr(model));
      // Calculate the normal matrix on the CPU (keep them normals perpendicular).
      normal = glm::mat3(glm::transpose(glm::inverse(model)));
      glUniformMatrix3fv(normalMatrix, 1, GL_FALSE, glm::value_ptr(normal));
      // Draw the container.
      glDrawArrays(GL_TRIANGLES, 0, 36);
    }
    glBindVertexArray(0);

    // Bind the VAO and shader.
    glBindVertexArray(lightVAO);
    lampShader.use();

    // Pass the view and projection matrices from the camera.
    viewMatrix = glGetUniformLocation(lampShader.program, "view");
    glUniformMatrix4fv(viewMatrix, 1, GL_FALSE, glm::value_ptr(camera.view));
    projectionMatrix = glGetUniformLocation(lampShader.program, "projection");
    glUniformMatrix4fv(projectionMatrix, 1, GL_FALSE, glm::value_ptr(camera.projection));

    for (GLuint i = 0; i < 4; i++) {
      // Apply world transformations.
      model = glm::mat4();
      model = glm::translate(model, pointLightPositions[i]);
      model = glm::scale(model, glm::vec3(0.2f));

      modelMatrix = glGetUniformLocation(lampShader.program, "model");
      glUniformMatrix4fv(modelMatrix, 1, GL_FALSE, glm::value_ptr(model));

      // Draw the lamp.
      glDrawArrays(GL_TRIANGLES, 0, 36);
    }
    glBindVertexArray(0);

    // Draw something with the geometry shader program.
    //glDisable(GL_DEPTH_TEST);
    //gsShader.use();
    //glBindVertexArray(pointsVAO);
    //glDrawArrays(GL_POINTS, 0, 4);
    //glBindVertexArray(0);
    //glEnable(GL_DEPTH_TEST);

    // Unbind the offscreen framebuffer containing the unprocessed frame.
    glBindFramebuffer(GL_FRAMEBUFFER, 0);
    glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);
    glDisable(GL_DEPTH_TEST);

    postShader.use();
    glBindVertexArray(frameVAO);

    // Send the texture sampler to the shader.
    GLuint frameTexture = glGetUniformLocation(postShader.program, "frameTexture");
    time = glGetUniformLocation(postShader.program, "time");
    glUniform1i(frameTexture, 0);
    glUniform1f(time, glfwGetTime());
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, frameColorBuffer);

    // Render the color buffer in the framebuffer to the quad with post shader.
    glDrawArrays(GL_TRIANGLES, 0, 6);
    glBindVertexArray(0);

    // Swap buffers used for double buffering.
    glfwSwapBuffers(window);
  }

  // Destroy the off screen framebuffer.
  glBindFramebuffer(GL_FRAMEBUFFER, 0);
  glDeleteFramebuffers(1, &FBO);

  // Properly deallocate the VBO and VAO.
  glDeleteVertexArrays(1, &VAO);
  glDeleteBuffers(1, &VBO);

  // Terminate GLFW and clean any resources before exiting.
  glfwTerminate();

  return 0;
}
Пример #22
0
/*******************************************************************************
 * Function Name : DrawModel
 * Description   : Draws the model
 *******************************************************************************/
void OGLES2Shaders::DrawModel()
{
	// Use the loaded effect
	m_ppEffect[m_nCurrentShader]->Activate();

	/*
		Set attributes and uniforms
	*/
	const CPVRTArray<SPVRTPFXUniform>& Uniforms = m_ppEffect[m_nCurrentShader]->GetUniformArray();

	for(unsigned int j = 0; j < Uniforms.GetSize(); ++j)
	{

		switch(Uniforms[j].nSemantic)
		{
		case ePVRTPFX_UsPOSITION:
			{
				glBindBuffer(GL_ARRAY_BUFFER, m_Surface->iVertexVBO);
				glVertexAttribPointer(Uniforms[j].nLocation, 3, GL_FLOAT, GL_FALSE, 0, (const void*) NULL);
				glEnableVertexAttribArray(Uniforms[j].nLocation);
			}
			break;
		case ePVRTPFX_UsNORMAL:
			{
				glBindBuffer(GL_ARRAY_BUFFER, m_Surface->iNormalVBO);
				glVertexAttribPointer(Uniforms[j].nLocation, 3, GL_FLOAT, GL_FALSE, 0, (const void*) NULL);
				glEnableVertexAttribArray(Uniforms[j].nLocation);
			}
			break;
		case ePVRTPFX_UsUV:
			{
				glBindBuffer(GL_ARRAY_BUFFER, m_Surface->iUvVBO);
				glVertexAttribPointer(Uniforms[j].nLocation, 2, GL_FLOAT, GL_FALSE, 0, (const void*) NULL);
				glEnableVertexAttribArray(Uniforms[j].nLocation);
			}
			break;
		case ePVRTPFX_UsWORLDVIEWPROJECTION:
			{
				PVRTMat4 mMVP;

				/* Passes the model-view-projection matrix (MVP) to the shader to transform the vertices */
				mMVP = m_mProjection * m_mModelView;
				glUniformMatrix4fv(Uniforms[j].nLocation, 1, GL_FALSE, mMVP.f);
			}
			break;
		case ePVRTPFX_UsWORLDVIEW:
			{
				glUniformMatrix4fv(Uniforms[j].nLocation, 1, GL_FALSE, m_mModelView.f);
			}
			break;
		case ePVRTPFX_UsWORLDVIEWIT:
			{
				PVRTMat4 mModelViewI, mModelViewIT;

				/* Passes the inverse transpose of the model-view matrix to the shader to transform the normals */
				mModelViewI = m_mModelView.inverse();
				mModelViewIT= mModelViewI.transpose();
				PVRTMat3 ModelViewIT = PVRTMat3(mModelViewIT);

				glUniformMatrix3fv(Uniforms[j].nLocation, 1, GL_FALSE, ModelViewIT.f);
			}
			break;
		case ePVRTPFX_UsVIEWIT:
			{
				PVRTMat4 mViewI, mViewIT;

				/* Passes the inverse transpose of the model-view matrix to the shader to transform the normals */
				mViewI = m_mView.inverse();
				mViewIT= mViewI.transpose();

				PVRTMat3 ViewIT = PVRTMat3(mViewIT);

				glUniformMatrix3fv(Uniforms[j].nLocation, 1, GL_FALSE, ViewIT.f);
			}
			break;
		case ePVRTPFX_UsTEXTURE:
			{
				// Set the sampler variable to the texture unit
				glUniform1i(Uniforms[j].nLocation, Uniforms[j].nIdx);
			}
			break;
		case ePVRTPFX_UsANIMATION:
			{
				// Float in the range 0..1: contains this objects distance through its animation.
				float fAnimation = 0.5f * m_fViewAngle / PVRT_PI;
				glUniform1f(Uniforms[j].nLocation, fAnimation);
			}
			break;
		}
	}

	glBindBuffer(GL_ARRAY_BUFFER, 0);	// Unbind the last buffer used.

	glDrawElements(GL_TRIANGLES, m_Surface->GetNumFaces()*3, GL_UNSIGNED_SHORT, m_Surface->pIndex);

	/*
		Disable attributes
	*/
	for(unsigned int j = 0; j < Uniforms.GetSize(); ++j)
	{
		switch(Uniforms[j].nSemantic)
		{
		case ePVRTPFX_UsPOSITION:
			{
				glDisableVertexAttribArray(Uniforms[j].nLocation);
			}
			break;
		case ePVRTPFX_UsNORMAL:
			{
				glDisableVertexAttribArray(Uniforms[j].nLocation);
			}
			break;
		case ePVRTPFX_UsUV:
			{
				glDisableVertexAttribArray(Uniforms[j].nLocation);
			}
			break;
		}
	}

	return;
}
Пример #23
0
	void Shader::uniform(std::string attributeName, const glm::mat3 &value)
	{
		glUniformMatrix3fv(getUniformLocation(attributeName), 1, 0, glm::value_ptr(value));
	}
Пример #24
0
void program_draw(void *ptr)
{
    PROGRAM *program = (PROGRAM *)ptr;

    for (auto it=program->uniform_map.begin(); it!=program->uniform_map.end(); ++it){
        auto    &name = it->first;
        auto    &uniform = it->second;

        if (uniform.constant) {
            continue;
        } else if (name == "MODELVIEWPROJECTIONMATRIX") {
            glUniformMatrix4fv(uniform.location,
                               1,
                               GL_FALSE,
                               gfx->get_modelview_projection_matrix().m());
        } else if (name == TM_Diffuse_String) {
            glUniform1i(uniform.location, TM_Diffuse);

            uniform.constant = true;
        } else if (name == TM_Bump_String) {
            glUniform1i(uniform.location, TM_Bump);

            uniform.constant = true;
        } else if (name == "MODELVIEWMATRIX") {
            // Matrix Data
            glUniformMatrix4fv(uniform.location,
                               1,
                               GL_FALSE,
                               gfx->get_modelview_matrix().m());
        } else if (name == "PROJECTIONMATRIX") {
            glUniformMatrix4fv(uniform.location,
                               1,
                               GL_FALSE,
                               gfx->get_projection_matrix().m());

            uniform.constant = true;
        } else if (name == "NORMALMATRIX") {
            glUniformMatrix3fv(uniform.location,
                               1,
                               GL_FALSE,
                               gfx->get_normal_matrix().m());
        } else if (name == "MATERIAL.ambient") {
            // Material Data
            glUniform4fv(uniform.location,
                         1,
                         objmesh->current_material->ambient.v());
            /* In this scene, all the materials (in this case, there are
             * only two) have the exact same properties, so simply tag the
             * uniforms for the current material to be constant.  This will
             * also allow you to get better performance at runtime, because
             * the data will not be sent over and over for nothing.
             */
            uniform.constant = true;
        } else if (name == "MATERIAL.diffuse") {
            glUniform4fv(uniform.location,
                         1,
                         objmesh->current_material->diffuse.v());

            uniform.constant = true;
        } else if (name == "MATERIAL.specular") {
            glUniform4fv(uniform.location,
                         1,
                         objmesh->current_material->specular.v());

            uniform.constant = true;
        } else if (name == "MATERIAL.shininess") {
            glUniform1f(uniform.location,
                        objmesh->current_material->specular_exponent * 0.128f);
            
            uniform.constant = true;
        }
    }

    /* Since your lamps are now in an array, simply loop and dynamically
     * create the uniform name for the lamp index in the shader program,
     * and gather the necessary data for a specific lamp index as long as
     * the loop is rolling.
     */
    for (int i=0; i != MAX_LAMP; ++i)
        lamp[i]->push_to_shader(gfx, program, i);
}
Пример #25
0
		void program::uniform(const std::string& name, size_t count, bool transpose, const std::vector<glm::mat3>& values) noexcept {
			glUniformMatrix3fv(resolve_uniform_location(name), count, transpose, reinterpret_cast<const float*>(values.data()));
		}
Пример #26
0
void Program::setUniformMatrix3 (const GLchar *name, const glm::mat3 &v) {
	if(!isCurrent())
		throw std::runtime_error("A uniform tried to be set to a non-current program");
	glUniformMatrix3fv(uniform(name), 1, GL_FALSE, glm::value_ptr(v));
}
Пример #27
0
	void UniformHandler::BindFrameUniform(const Uniform& sUniform)
	{
		EUniformSemantic eSemantic = sUniform.getSemantic();
		unsigned int index = sUniform.getIdx();
		_ASSERT(getFlag(eSemantic,index));

		switch(eSemantic)
		{
		case eUsVIEW:
			{
				glUniformMatrix4fv(sUniform.getLocation(), 1, GL_FALSE, m_mView.f);
			}
			break;
		case eUsVIEWI:
			{
				glUniformMatrix4fv(sUniform.getLocation(), 1, GL_FALSE, m_mViewI.f);
			}
			break;
		case eUsVIEWIT:
			{
				glUniformMatrix3fv(sUniform.getLocation(), 1, GL_FALSE, m_mViewIT.f);
			}
			break;
		case eUsPROJECTION:
			{
				glUniformMatrix4fv(sUniform.getLocation(), 1, GL_FALSE, m_mProjection.f);
			}
			break;
		case eUsPROJECTIONI:
			{
				glUniformMatrix4fv(sUniform.getLocation(), 1, GL_FALSE, m_mProjectionI.f);
			}
			break;
		case eUsPROJECTIONIT:
			{
				glUniformMatrix3fv(sUniform.getLocation(), 1, GL_FALSE, m_mProjectionIT.f);
			}
			break;
		case eUsVIEWPROJECTION:
			{
				glUniformMatrix4fv(sUniform.getLocation(), 1, GL_FALSE, m_mViewProjection.f);
			}
			break;
		case eUsVIEWPROJECTIONI:
			{
				glUniformMatrix4fv(sUniform.getLocation(), 1, GL_FALSE, m_mViewProjectionI.f);
			}
			break;
		case eUsVIEWPROJECTIONIT:
			{
				glUniformMatrix3fv(sUniform.getLocation(), 1, GL_FALSE, m_mViewProjectionIT.f);
			}
			break;
		case eUsLIGHTCOLOR:
			{
				glUniform3f(sUniform.getLocation(), m_pfLightColor[index][0],
					m_pfLightColor[index][1], m_pfLightColor[index][2]);
			}
			break;
		case eUsLIGHTPOSWORLD:
			{
				glUniform3f(sUniform.getLocation(), m_vLightPosWorld[index].x,
					m_vLightPosWorld[index].y, m_vLightPosWorld[index].z);
			}
			break;
		case eUsLIGHTPOSEYE:
			{
				glUniform3f(sUniform.getLocation(), m_vLightPosEye[index].x,
					m_vLightPosEye[index].y, m_vLightPosEye[index].z);
			}
			break;
		case eUsLIGHTDIRWORLD:
			{
				glUniform3f(sUniform.getLocation(), m_vLightDirWorld[index].x,
					m_vLightDirWorld[index].y, m_vLightDirWorld[index].z);
			}
			break;
		case eUsLIGHTDIREYE:
			{
				glUniform3f(sUniform.getLocation(), m_vLightDirEye[index].x,
					m_vLightDirEye[index].y, m_vLightDirEye[index].z);
			}
			break;
		case eUsEYEPOSWORLD:
			{
				glUniform3f(sUniform.getLocation(),
					m_vEyePositionWorld.x, m_vEyePositionWorld.y, m_vEyePositionWorld.z);
			}
			break;
		case eUsANIMATION:
			{
				glUniform1f(sUniform.getLocation(), m_fAnimation);
			}
			break;
		default:
			{	// something went wrong
				ConsoleLog::inst().log("Error: non-frame uniform being interpreted as frame uniform\n");
				return;
			}
		}
	}
Пример #28
0
void AffineUnit::process_package(LoadPackage *package)
{
	AffinePackage *pkg = (AffinePackage*)package;
	int min_in_x = server->in_x;
	int min_in_y = server->in_y;
	int max_in_x = server->in_x + server->in_w - 1;
	int max_in_y = server->in_y + server->in_h - 1;

	int min_out_x = server->out_x;
	int min_out_y = server->out_y;
	int max_out_x = server->out_x + server->out_w;
	int max_out_y = server->out_y + server->out_h;

// Amount to shift the input coordinates relative to the output coordinates
// To get the pivots to line up
	int pivot_offset_x = server->in_pivot_x - server->out_pivot_x;
	int pivot_offset_y = server->in_pivot_y - server->out_pivot_y;

// Calculate real coords
	float out_x1, out_y1, out_x2, out_y2, out_x3, out_y3, out_x4, out_y4;
	if(server->mode == AffineEngine::STRETCH ||
		server->mode == AffineEngine::PERSPECTIVE ||
		server->mode == AffineEngine::ROTATE)
	{
		out_x1 = (float)server->in_x + (float)server->x1 * server->in_w / 100;
		out_y1 = (float)server->in_y + (float)server->y1 * server->in_h / 100;
		out_x2 = (float)server->in_x + (float)server->x2 * server->in_w / 100;
		out_y2 = (float)server->in_y + (float)server->y2 * server->in_h / 100;
		out_x3 = (float)server->in_x + (float)server->x3 * server->in_w / 100;
		out_y3 = (float)server->in_y + (float)server->y3 * server->in_h / 100;
		out_x4 = (float)server->in_x + (float)server->x4 * server->in_w / 100;
		out_y4 = (float)server->in_y + (float)server->y4 * server->in_h / 100;
	}
	else
	{
		out_x1 = (float)server->in_x + (float)server->x1 * server->in_w / 100;
		out_y1 = server->in_y;
		out_x2 = out_x1 + server->in_w;
		out_y2 = server->in_y;
		out_x4 = (float)server->in_x + (float)server->x4 * server->in_w / 100;
		out_y4 = server->in_y + server->in_h;
		out_x3 = out_x4 + server->in_w;
		out_y3 = server->in_y + server->in_h;
	}
// Rotation with OpenGL uses a simple quad.
	if(server->mode == AffineEngine::ROTATE &&
		server->use_opengl)
	{
#ifdef HAVE_GL
		server->output->to_texture();
		server->output->enable_opengl();
		server->output->init_screen();
		server->output->bind_texture(0);
		server->output->clear_pbuffer();

		int texture_w = server->output->get_texture_w();
		int texture_h = server->output->get_texture_h();
		float output_h = server->output->get_h();
		float in_x1 = (float)server->in_x / texture_w;
		float in_x2 = (float)(server->in_x + server->in_w) / texture_w;
		float in_y1 = (float)server->in_y / texture_h;
		float in_y2 = (float)(server->in_y + server->in_h) / texture_h;

		glBegin(GL_QUADS);
		glNormal3f(0, 0, 1.0);

		glTexCoord2f(in_x1, in_y1);
		glVertex3f(out_x1, -output_h+out_y1, 0);

		glTexCoord2f(in_x2, in_y1);
		glVertex3f(out_x2, -output_h+out_y2, 0);

		glTexCoord2f(in_x2, in_y2);
		glVertex3f(out_x3, -output_h+out_y3, 0);

		glTexCoord2f(in_x1, in_y2);
		glVertex3f(out_x4, -output_h+out_y4, 0);

		glEnd();

		server->output->set_opengl_state(VFrame::SCREEN);
#endif
	}
	else
	if(server->mode == AffineEngine::PERSPECTIVE ||
		server->mode == AffineEngine::SHEER ||
		server->mode == AffineEngine::ROTATE)
	{
		AffineMatrix matrix;
		float temp;
// swap points 3 & 4
		temp = out_x4;
		out_x4 = out_x3;
		out_x3 = temp;
		temp = out_y4;
		out_y4 = out_y3;
		out_y3 = temp;

		calculate_matrix(
			server->in_x,
			server->in_y,
			server->in_x + server->in_w,
			server->in_y + server->in_h,
			out_x1,
			out_y1,
			out_x2,
			out_y2,
			out_x3,
			out_y3,
			out_x4,
			out_y4,
			&matrix);

		int interpolate = 1;
		int reverse = !server->forward;
		float tx, ty, tw;
		float xinc, yinc, winc;
		AffineMatrix m, im;
		float ttx = 0, tty = 0;
		int itx = 0, ity = 0;
		int tx1 = 0, ty1 = 0, tx2 = 0, ty2 = 0;

		if(reverse)
		{
			m.copy_from(&matrix);
			m.invert(&im);
			matrix.copy_from(&im);
		}
		else
		{
			matrix.invert(&m);
		}

		float dx1 = 0, dy1 = 0;
		float dx2 = 0, dy2 = 0;
		float dx3 = 0, dy3 = 0;
		float dx4 = 0, dy4 = 0;
		matrix.transform_point(server->in_x, server->in_y, &dx1, &dy1);
		matrix.transform_point(server->in_x + server->in_w, server->in_y, &dx2, &dy2);
		matrix.transform_point(server->in_x, server->in_y + server->in_h, &dx3, &dy3);
		matrix.transform_point(server->in_x + server->in_w, server->in_y + server->in_h, &dx4, &dy4);

		if(server->use_opengl)
		{
#ifdef HAVE_GL
			static char *affine_frag =
				(char*)"uniform sampler2D tex;\n"
				"uniform mat3 affine_matrix;\n"
				"uniform vec2 texture_extents;\n"
				"uniform vec2 image_extents;\n"
				"uniform vec4 border_color;\n"
				"void main()\n"
				"{\n"
				"	vec2 outcoord = gl_TexCoord[0].st;\n"
				"	outcoord *= texture_extents;\n"
				"	mat3 coord_matrix = mat3(\n"
				"		outcoord.x, outcoord.y, 1.0, \n"
				"		outcoord.x, outcoord.y, 1.0, \n"
				"		outcoord.x, outcoord.y, 1.0);\n"
				"	mat3 incoord_matrix = affine_matrix * coord_matrix;\n"
				"	vec2 incoord = vec2(incoord_matrix[0][0], incoord_matrix[0][1]);\n"
				"	incoord /= incoord_matrix[0][2];\n"
				"	incoord /= texture_extents;\n"
				"	if(incoord.x > image_extents.x || incoord.y > image_extents.y)\n"
				"		gl_FragColor = border_color;\n"
				"	else\n"
				"		gl_FragColor = texture2D(tex, incoord);\n"
				"}\n";

			float affine_matrix[9] = {
				(float)m.values[0][0], (float)m.values[1][0], (float)m.values[2][0],
				(float)m.values[0][1], (float)m.values[1][1], (float)m.values[2][1],
				(float)m.values[0][2], (float)m.values[1][2], (float)m.values[2][2]
			};

			server->output->to_texture();
			server->output->enable_opengl();
			unsigned int frag_shader = VFrame::make_shader(0,
					affine_frag,
					0);
			if(frag_shader > 0)
			{
				glUseProgram(frag_shader);
				glUniform1i(glGetUniformLocation(frag_shader, "tex"), 0);
				glUniformMatrix3fv(glGetUniformLocation(frag_shader, "affine_matrix"), 
					1,
					0,
					affine_matrix);
				glUniform2f(glGetUniformLocation(frag_shader, "texture_extents"), 
					(GLfloat)server->output->get_texture_w(),
					(GLfloat)server->output->get_texture_h());
				glUniform2f(glGetUniformLocation(frag_shader, "image_extents"), 
					(GLfloat)server->output->get_w() / server->output->get_texture_w(),
					(GLfloat)server->output->get_h() / server->output->get_texture_h());
				float border_color[] = { 0, 0, 0, 0 };
				if(BC_CModels::is_yuv(server->output->get_color_model()))
				{
					border_color[1] = 0.5;
					border_color[2] = 0.5;
				}
				if(!BC_CModels::has_alpha(server->output->get_color_model()))
				{
					border_color[3] = 1.0;
				}

				glUniform4fv(glGetUniformLocation(frag_shader, "border_color"), 
					1,
					(GLfloat*)border_color);
				server->output->init_screen();
				server->output->bind_texture(0);
				glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, border_color);
				glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
				glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
				server->output->draw_texture();
				glUseProgram(0);
				server->output->set_opengl_state(VFrame::SCREEN);
			}
			return;
#endif // HAVE_GL
		}

#define ROUND(x) ((int)((x > 0) ? (x) + 0.5 : (x) - 0.5))
#define MIN4(a,b,c,d) MIN(MIN(MIN(a,b),c),d)
#define MAX4(a,b,c,d) MAX(MAX(MAX(a,b),c),d)

		tx1 = ROUND(MIN4(dx1 - pivot_offset_x, dx2 - pivot_offset_x, dx3 - pivot_offset_x, dx4 - pivot_offset_x));
		ty1 = ROUND(MIN4(dy1 - pivot_offset_y, dy2 - pivot_offset_y, dy3 - pivot_offset_y, dy4 - pivot_offset_y));

		tx2 = ROUND(MAX4(dx1 - pivot_offset_x, dx2 - pivot_offset_x, dx3 - pivot_offset_x, dx4 - pivot_offset_x));
		ty2 = ROUND(MAX4(dy1 - pivot_offset_y, dy2 - pivot_offset_y, dy3 - pivot_offset_y, dy4 - pivot_offset_y));

		CLAMP(ty1, pkg->y1, pkg->y2);
		CLAMP(ty2, pkg->y1, pkg->y2);
		CLAMP(tx1, server->out_x, server->out_x + server->out_w);
		CLAMP(tx2, server->out_x, server->out_x + server->out_w);

		xinc = m.values[0][0];
		yinc = m.values[1][0];
		winc = m.values[2][0];

#define CUBIC_ROW(in_row, chroma_offset) \
	transform_cubic(dx, \
		in_row[col1_offset] - chroma_offset, \
		in_row[col2_offset] - chroma_offset, \
		in_row[col3_offset] - chroma_offset, \
		in_row[col4_offset] - chroma_offset)


#define TRANSFORM(components, type, temp_type, chroma_offset, max) \
{ \
	type **in_rows = (type**)server->input->get_rows(); \
	float round_factor = 0.0; \
	if(sizeof(type) < 4) round_factor = 0.5; \
	for(int y = ty1; y < ty2; y++) \
	{ \
		type *out_row = (type*)server->output->get_rows()[y]; \
 \
		if(!interpolate) \
		{ \
        	tx = xinc * (tx1 + 0.5) + \
				m.values[0][1] * (y + pivot_offset_y + 0.5) + \
				m.values[0][2] + \
				pivot_offset_x * xinc; \
        	ty = yinc * (tx1 + 0.5) + \
				m.values[1][1] * (y + pivot_offset_y + 0.5) + \
				m.values[1][2] + \
				pivot_offset_x * yinc; \
        	tw = winc * (tx1 + 0.5) + \
				m.values[2][1] * (y + pivot_offset_y + 0.5) + \
				m.values[2][2] + \
				pivot_offset_x * winc; \
		} \
		else \
		{ \
			tx = xinc * tx1 + \
				m.values[0][1] * (y + pivot_offset_y) + \
				m.values[0][2] + \
				pivot_offset_x * xinc; \
			ty = yinc * tx1 + \
				m.values[1][1] * (y + pivot_offset_y) + \
				m.values[1][2] + \
				pivot_offset_x * yinc; \
			tw = winc * tx1 + \
				m.values[2][1] * (y + pivot_offset_y) + \
				m.values[2][2] + \
				pivot_offset_x * winc; \
		} \
 \
		out_row += tx1 * components; \
		for(int x = tx1; x < tx2; x++) \
		{ \
/* Normalize homogeneous coords */ \
			if(tw == 0.0) \
			{ \
				ttx = 0.0; \
				tty = 0.0; \
			} \
			else \
			if(tw != 1.0) \
			{ \
				ttx = tx / tw; \
				tty = ty / tw; \
			} \
			else \
			{ \
				ttx = tx; \
				tty = ty; \
			} \
			itx = (int)ttx; \
			ity = (int)tty; \
 \
			int row1 = ity - 1; \
			int row2 = ity; \
			int row3 = ity + 1; \
			int row4 = ity + 2; \
			CLAMP(row1, min_in_y, max_in_y); \
			CLAMP(row2, min_in_y, max_in_y); \
			CLAMP(row3, min_in_y, max_in_y); \
			CLAMP(row4, min_in_y, max_in_y); \
 \
/* Set destination pixels if in clipping region */ \
			if(!interpolate && \
				x >= min_out_x && \
				x < max_out_x) \
			{ \
				if(itx >= min_in_x && \
					itx <= max_in_x && \
					ity >= min_in_y && \
					ity <= max_in_y) \
				{ \
					type *src = in_rows[ity] + itx * components; \
					*out_row++ = *src++; \
					*out_row++ = *src++; \
					*out_row++ = *src++; \
					if(components == 4) *out_row++ = *src; \
				} \
				else \
/* Fill with chroma */ \
				{ \
					*out_row++ = 0; \
					*out_row++ = chroma_offset; \
					*out_row++ = chroma_offset; \
					if(components == 4) *out_row++ = 0; \
				} \
			} \
			else \
/* Bicubic algorithm */ \
			if(interpolate &&  \
				x >= min_out_x &&  \
				x < max_out_x) \
			{ \
/* clipping region */ \
				if ((itx + 2) >= min_in_x && \
					(itx - 1) <= max_in_x && \
					(ity + 2) >= min_in_y && \
					(ity - 1) <= max_in_y) \
				{ \
					float dx, dy; \
 \
/* the fractional error */ \
					dx = ttx - itx; \
					dy = tty - ity; \
 \
/* Row and column offsets in cubic block */ \
					int col1 = itx - 1; \
					int col2 = itx; \
					int col3 = itx + 1; \
					int col4 = itx + 2; \
					CLAMP(col1, min_in_x, max_in_x); \
					CLAMP(col2, min_in_x, max_in_x); \
					CLAMP(col3, min_in_x, max_in_x); \
					CLAMP(col4, min_in_x, max_in_x); \
					int col1_offset = col1 * components; \
					int col2_offset = col2 * components; \
					int col3_offset = col3 * components; \
					int col4_offset = col4 * components; \
 \
					type *row1_ptr = in_rows[row1]; \
					type *row2_ptr = in_rows[row2]; \
					type *row3_ptr = in_rows[row3]; \
					type *row4_ptr = in_rows[row4]; \
					temp_type r, g, b, a; \
 \
					r = (temp_type)(transform_cubic(dy, \
						CUBIC_ROW(row1_ptr, 0x0), \
						CUBIC_ROW(row2_ptr, 0x0), \
						CUBIC_ROW(row3_ptr, 0x0), \
						CUBIC_ROW(row4_ptr, 0x0)) + \
						round_factor); \
 \
					row1_ptr++; \
					row2_ptr++; \
					row3_ptr++; \
					row4_ptr++; \
					g = (temp_type)(transform_cubic(dy, \
						CUBIC_ROW(row1_ptr, chroma_offset), \
						CUBIC_ROW(row2_ptr, chroma_offset), \
						CUBIC_ROW(row3_ptr, chroma_offset), \
						CUBIC_ROW(row4_ptr, chroma_offset)) + \
						round_factor); \
					g += chroma_offset; \
 \
					row1_ptr++; \
					row2_ptr++; \
					row3_ptr++; \
					row4_ptr++; \
					b = (temp_type)(transform_cubic(dy, \
						CUBIC_ROW(row1_ptr, chroma_offset), \
						CUBIC_ROW(row2_ptr, chroma_offset), \
						CUBIC_ROW(row3_ptr, chroma_offset), \
						CUBIC_ROW(row4_ptr, chroma_offset)) + \
						round_factor); \
					b += chroma_offset; \
 \
					if(components == 4) \
					{ \
						row1_ptr++; \
						row2_ptr++; \
						row3_ptr++; \
						row4_ptr++; \
						a = (temp_type)(transform_cubic(dy, \
							CUBIC_ROW(row1_ptr, 0x0), \
							CUBIC_ROW(row2_ptr, 0x0), \
							CUBIC_ROW(row3_ptr, 0x0), \
							CUBIC_ROW(row4_ptr, 0x0)) +  \
							round_factor); \
					} \
 \
 					if(sizeof(type) < 4) \
					{ \
						*out_row++ = CLIP(r, 0, max); \
						*out_row++ = CLIP(g, 0, max); \
						*out_row++ = CLIP(b, 0, max); \
						if(components == 4) *out_row++ = CLIP(a, 0, max); \
					} \
					else \
					{ \
						*out_row++ = r; \
						*out_row++ = g; \
						*out_row++ = b; \
						if(components == 4) *out_row++ = a; \
					} \
				} \
				else \
/* Fill with chroma */ \
				{ \
					*out_row++ = 0; \
					*out_row++ = chroma_offset; \
					*out_row++ = chroma_offset; \
					if(components == 4) *out_row++ = 0; \
				} \
			} \
			else \
			{ \
				out_row += components; \
			} \
 \
/*  increment the transformed coordinates  */ \
			tx += xinc; \
			ty += yinc; \
			tw += winc; \
		} \
	} \
}

		switch(server->input->get_color_model())
		{
		case BC_RGB_FLOAT:
			TRANSFORM(3, float, float, 0x0, 1.0)
			break;
		case BC_RGB888:
			TRANSFORM(3, unsigned char, int, 0x0, 0xff)
			break;
		case BC_RGBA_FLOAT:
			TRANSFORM(4, float, float, 0x0, 1.0)
			break;
		case BC_RGBA8888:
			TRANSFORM(4, unsigned char, int, 0x0, 0xff)
			break;
		case BC_YUV888:
			{
				unsigned char **in_rows = (unsigned char**)server->input->get_rows();
				float round_factor = 0.0;
				if(sizeof(unsigned char) < 4) round_factor = 0.5;
				for(int y = ty1; y < ty2; y++)
				{
					unsigned char *out_row = (unsigned char*)server->output->get_rows()[y];

					if(!interpolate)
					{
						tx = xinc * (tx1 + 0.5) +
							m.values[0][1] * (y + pivot_offset_y + 0.5) +
							m.values[0][2] +
							pivot_offset_x * xinc;
						ty = yinc * (tx1 + 0.5) +
							m.values[1][1] * (y + pivot_offset_y + 0.5) +
							m.values[1][2] +
							pivot_offset_x * yinc;
						tw = winc * (tx1 + 0.5) +
							m.values[2][1] * (y + pivot_offset_y + 0.5) +
							m.values[2][2] +
							pivot_offset_x * winc;
					}
					else
					{
						tx = xinc * tx1 +
							m.values[0][1] * (y + pivot_offset_y) +
							m.values[0][2] +
							pivot_offset_x * xinc;
						ty = yinc * tx1 +
							m.values[1][1] * (y + pivot_offset_y) +
							m.values[1][2] +
							pivot_offset_x * yinc;
						tw = winc * tx1 +
							m.values[2][1] * (y + pivot_offset_y) +
							m.values[2][2] +
							pivot_offset_x * winc;
					}

					out_row += tx1 * 3;
					for(int x = tx1; x < tx2; x++)
					{
// Normalize homogeneous coords
						if(tw == 0.0)
						{
							ttx = 0.0;
							tty = 0.0;
						}
						else
						if(tw != 1.0)
						{
							ttx = tx / tw;
							tty = ty / tw;
						}
						else
						{
							ttx = tx;
							tty = ty;
						}
						itx = (int)ttx;
						ity = (int)tty;

						int row1 = ity - 1;
						int row2 = ity;
						int row3 = ity + 1;
						int row4 = ity + 2;
						CLAMP(row1, min_in_y, max_in_y);
						CLAMP(row2, min_in_y, max_in_y);
						CLAMP(row3, min_in_y, max_in_y);
						CLAMP(row4, min_in_y, max_in_y);
// Set destination pixels if in clipping region
						if(!interpolate &&
							x >= min_out_x &&
							x < max_out_x)
						{
							if(itx >= min_in_x &&
								itx <= max_in_x &&
								ity >= min_in_y &&
								ity <= max_in_y)
							{
								unsigned char *src = in_rows[ity] + itx * 3;
								*out_row++ = *src++;
								*out_row++ = *src++;
								*out_row++ = *src++;
							}
							else
// Fill with chroma
							{
								*out_row++ = 0;
								*out_row++ = 0x80;
								*out_row++ = 0x80;
							}
						}
						else
// Bicubic algorithm
						if(interpolate &&
							x >= min_out_x &&
							x < max_out_x)
						{
// clipping region
							if((itx + 2) >= min_in_x &&
								(itx - 1) <= max_in_x &&
								(ity + 2) >= min_in_y &&
								(ity - 1) <= max_in_y)
							{
								float dx, dy;
// the fractional error
								dx = ttx - itx;
								dy = tty - ity;
// Row and column offsets in cubic block
								int col1 = itx - 1;
								int col2 = itx;
								int col3 = itx + 1;
								int col4 = itx + 2;
								CLAMP(col1, min_in_x, max_in_x);
								CLAMP(col2, min_in_x, max_in_x);
								CLAMP(col3, min_in_x, max_in_x);
								CLAMP(col4, min_in_x, max_in_x);

								int col1_offset = col1 * 3;
								int col2_offset = col2 * 3;
								int col3_offset = col3 * 3;
								int col4_offset = col4 * 3;

								unsigned char *row1_ptr = in_rows[row1];
								unsigned char *row2_ptr = in_rows[row2];
								unsigned char *row3_ptr = in_rows[row3];
								unsigned char *row4_ptr = in_rows[row4];
								int r, g, b, a;

								r = (int)(transform_cubic(dy,
									CUBIC_ROW(row1_ptr, 0x0),
									CUBIC_ROW(row2_ptr, 0x0),
									CUBIC_ROW(row3_ptr, 0x0),
									CUBIC_ROW(row4_ptr, 0x0)) +
									round_factor);

								row1_ptr++;
								row2_ptr++;
								row3_ptr++;
								row4_ptr++;
								g = (int)(transform_cubic(dy,
									CUBIC_ROW(row1_ptr, 0x80),
									CUBIC_ROW(row2_ptr, 0x80),
									CUBIC_ROW(row3_ptr, 0x80),
									CUBIC_ROW(row4_ptr, 0x80)) +
									round_factor);
								g += 0x80;

								row1_ptr++;
								row2_ptr++;
								row3_ptr++;
								row4_ptr++;
								b = (int)(transform_cubic(dy,
									CUBIC_ROW(row1_ptr, 0x80),
									CUBIC_ROW(row2_ptr, 0x80),
									CUBIC_ROW(row3_ptr, 0x80),
									CUBIC_ROW(row4_ptr, 0x80)) +
									round_factor);
								b += 0x80;

								if(sizeof(unsigned char) < 4)
								{
									*out_row++ = CLIP(r, 0, 0xff);
									*out_row++ = CLIP(g, 0, 0xff);
									*out_row++ = CLIP(b, 0, 0xff);
								}
								else
								{
									*out_row++ = r;
									*out_row++ = g;
									*out_row++ = b;
								}
							}
							else
// Fill with chroma
							{
								*out_row++ = 0;
								*out_row++ = 0x80;
								*out_row++ = 0x80;
							}
						}
						else
						{
							out_row += 3;
						}

//  increment the transformed coordinates
						tx += xinc;
						ty += yinc;
						tw += winc;
					}
				}
			}

			break;
		case BC_YUVA8888:
			TRANSFORM(4, unsigned char, int, 0x80, 0xff)
			break;
		case BC_RGB161616:
			TRANSFORM(3, uint16_t, int, 0x0, 0xffff)
			break;
		case BC_RGBA16161616:
			TRANSFORM(4, uint16_t, int, 0x0, 0xffff)
			break;
		case BC_YUV161616:
			TRANSFORM(3, uint16_t, int, 0x8000, 0xffff)
			break;
		case BC_YUVA16161616:
			TRANSFORM(4, uint16_t, int, 0x8000, 0xffff)
			break;
		}
	}
Пример #29
0
void GL::uniformMatrix3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value) {
    GL_CHECK(glUniformMatrix3fv(location, count, transpose, value));
}
Пример #30
0
void setUniform(GLint uni, glm::mat3 & value)
{
	glUniformMatrix3fv(uni, 1, GL_FALSE, glm::value_ptr(value));
}