Exemplo n.º 1
0
void Shader::setParameter(const std::string& name, float x, float y, float z)
{
    if (m_shaderProgram)
    {
        ensureGlContext();

        // Enable program
        GLhandleARB program = glGetHandleARB(GL_PROGRAM_OBJECT_ARB);
        glCheck(glUseProgramObjectARB(m_shaderProgram));

        // Get parameter location and assign it new values
        GLint location = glGetUniformLocationARB(m_shaderProgram, name.c_str());
        if (location != -1)
            glCheck(glUniform3fARB(location, x, y, z));
        else
            err() << "Parameter \"" << name << "\" not found in shader" << std::endl;

        // Disable program
        glCheck(glUseProgramObjectARB(program));
    }
}
Exemplo n.º 2
0
void Shader::SetParameter(const std::string& name, const sf::Transform& transform)
{
    if (myShaderProgram)
    {
        EnsureGlContext();

        // Enable program
        GLhandleARB program = glGetHandleARB(GL_PROGRAM_OBJECT_ARB);
        GLCheck(glUseProgramObjectARB(myShaderProgram));

        // Get parameter location and assign it new values
        GLint location = glGetUniformLocationARB(myShaderProgram, name.c_str());
        if (location != -1)
            GLCheck(glUniformMatrix4fvARB(location, 1, GL_FALSE, transform.GetMatrix()));
        else
            Err() << "Parameter \"" << name << "\" not found in shader" << std::endl;

        // Disable program
        GLCheck(glUseProgramObjectARB(program));
    }
}
Exemplo n.º 3
0
	void draw() {
		glUseProgram(shaderProgram);
		int projectionMatrixLocation = glGetUniformLocation(shaderProgram, "projectionMatrix");
		int viewMatrixLocation = glGetUniformLocation(shaderProgram, "viewMatrix");
		int modelMatrixLocation = glGetUniformLocation(shaderProgram, "modelMatrix");
		glUniformMatrix4fv(projectionMatrixLocation, 1, GL_FALSE, &projectionMatrix[0][0]); 
		glUniformMatrix4fv(viewMatrixLocation, 1, GL_FALSE, &viewMatrix[0][0]); 
		glUniformMatrix4fv(modelMatrixLocation, 1, GL_FALSE, &modelMatrix[0][0]); 

		int location = glGetUniformLocationARB(shaderProgram, "tex");
		glActiveTexture(GL_TEXTURE0);
		glBindTexture(GL_TEXTURE_2D, texture);
		glUniform1iARB(location, 0);

		glBindVertexArray(vbo);
		glBindBuffer(GL_ARRAY_BUFFER, vbo);
		glEnableVertexAttribArray( vbo );

		glVertexAttribPointer(vbo, 3, GL_FLOAT, GL_FALSE, sizeof(float)*3, 0);
		glDrawArrays( GL_TRIANGLE_STRIP, 0, numVertices );
	}
Exemplo n.º 4
0
/*!
void Joints(Shaderobject shader, String uniform_variable)\n
script function to pass the transformed armature joint positions as uniform
array to a vertex shader 
*/
void Item_armature::Joints(QObject* _shader, QString var){
	if (glwrapper_shader* shader = dynamic_cast<glwrapper_shader*>(_shader)){
		float* space = new float[max_bone_id * 3 + 3];

		for (QTreeWidgetItemIterator it(this);*it;it++){
			if (Item_bone* bone = dynamic_cast<Item_bone*>(*it)){
				space[bone->id * 3 + 0]	= bone->joint[0];
				space[bone->id * 3 + 1]	= bone->joint[1];
				space[bone->id * 3 + 2]	= bone->joint[2];
				}
			}
		shader->Bind();
		int loc = glGetUniformLocationARB(shader->getShaderHandle(),var.toLatin1().constData());
		if(loc == -1) return;
		glUniform3fvARB(loc, max_bone_id + 1, space);
		delete[] space;
		
		}
	else{
		qDebug() << "Item_armature::Joints parameter is not a shader object";
		}
	}
Exemplo n.º 5
0
void GLShader::setShaderValue(const char *varId, float *value)
{
//	if (!program) return;

	if (shaderVals.find(varId) == shaderVals.end())
	{
//		if (shaderVals[varId].binding != -1) use();
		shaderVals[varId].binding = glGetUniformLocationARB(program, varId);
		shaderVals[varId].valType = SHADER_VAL_4X4;
		if (shaderVals[varId].binding!=-1) shaderVals[varId].mat = NULL;
		shaderVals[varId].mat = new float[16];
	}

	
//	if (shaderVals[varId].xyzVal.x != value)
//	{
//		if (!shaderVals[varId].mat) shaderVals[varId].mat = new float[16];
		memcpy(shaderVals[varId].mat,value,sizeof(float)*16);
//	}	
	
//	glUniformMatrix4fvARB(shaderVals[varId].binding,1,false,value);		
}
Exemplo n.º 6
0
CircleFieldRenderer::CircleFieldRenderer(const Manifold& m,
        bool smooth,
        VertexAttributeVector<Vec2d>& field,
        float gamma): SimpleShaderRenderer(vss, fss)
{

    GLint old_prog;
    glGetIntegerv(GL_CURRENT_PROGRAM, &old_prog);
    glUseProgram(prog);

    GLuint scalar_attrib = glGetAttribLocation(prog, "circlepos");

    //    static float& gamma = CreateCVar("display.scalar_field_renderer.gamma",2.2f);
    glUniform1fARB(glGetUniformLocationARB(prog, "gamma"), gamma);
    glNewList(display_list,GL_COMPILE);

    for(FaceIDIterator f = m.faces_begin(); f != m.faces_end(); ++f) {
        if(!smooth)
            glNormal3dv(normal(m, *f).get());
        if(no_edges(m, *f)== 3)
            glBegin(GL_TRIANGLES);
        else
            glBegin(GL_POLYGON);


        for(Walker w = m.walker(*f); !w.full_circle(); w = w.circulate_face_ccw()) {
            Vec3d n(normal(m, w.vertex()));
            if(smooth)
                glNormal3dv(n.get());
            glVertexAttrib2dv(scalar_attrib, field[w.vertex()].get());
            glVertex3dv(m.pos(w.vertex()).get());
        }
        glEnd();
    }
    glEndList();
    glUseProgram(old_prog);

}
Exemplo n.º 7
0
static void use_uniform(struct brush *b, struct uniform *u)
{
    int L;

    /* Apply the uniform values to the OpenGL state. */

    if (GL_has_shader_objects && u && b->shad_prog)
    {
        glUseProgramObjectARB(b->shad_prog);

        if ((L = glGetUniformLocationARB(b->shad_prog, u->name)) != -1)
        {
            const float *k = u->vals;

            int r = u->rows;
            int c = u->cols;

            if      (r == 0 && c == 0)
                glUniform1iARB(L, u->indx);

            else if (r == 1 && c == 1)
                glUniform1fARB(L, k[0]);
            else if (r == 1 && c == 2)
                glUniform2fARB(L, k[0], k[1]);
            else if (r == 1 && c == 3)
                glUniform3fARB(L, k[0], k[1], k[2]);
            else if (r == 1 && c == 4)
                glUniform4fARB(L, k[0], k[1], k[2], k[3]);

            else if (r == 2 && c == 2) glUniformMatrix2fvARB(L, 1, 0, k);
            else if (r == 3 && c == 3) glUniformMatrix3fvARB(L, 1, 0, k);
            else if (r == 4 && c == 4) glUniformMatrix4fvARB(L, 1, 0, k);
        }

        glUseProgramObjectARB(0);
    }
}
Exemplo n.º 8
0
void VoxGame::RenderFirstPassFullScreen()
{
	m_pRenderer->PushMatrix();
		m_pRenderer->SetProjectionMode(PM_2D, m_defaultViewport);
		m_pRenderer->SetLookAtCamera(vec3(0.0f, 0.0f, 250.0f), vec3(0.0f, 0.0f, 0.0f), vec3(0.0f, 1.0f, 0.0f));

		// Blur first pass (Horizontal)
		m_pRenderer->StartRenderingToFrameBuffer(m_secondPassFullscreenBuffer);
		m_pRenderer->BeginGLSLShader(m_blurHorizontalShader);
		glShader* pShader = m_pRenderer->GetShader(m_blurHorizontalShader);

		float blurSize = 0.0015f;

		unsigned int textureId0 = glGetUniformLocationARB(pShader->GetProgramObject(), "texture");
		m_pRenderer->PrepareShaderTexture(0, textureId0);
		m_pRenderer->BindRawTextureId(m_pRenderer->GetDiffuseTextureFromFrameBuffer(m_firstPassFullscreenBuffer));

		pShader->setUniform1f("blurSize", blurSize);

		m_pRenderer->SetRenderMode(RM_TEXTURED);
		m_pRenderer->EnableImmediateMode(IM_QUADS);
			m_pRenderer->ImmediateTextureCoordinate(0.0f, 0.0f);
			m_pRenderer->ImmediateVertex(0.0f, 0.0f, 1.0f);
			m_pRenderer->ImmediateTextureCoordinate(1.0f, 0.0f);
			m_pRenderer->ImmediateVertex((float)m_windowWidth, 0.0f, 1.0f);
			m_pRenderer->ImmediateTextureCoordinate(1.0f, 1.0f);
			m_pRenderer->ImmediateVertex((float)m_windowWidth, (float)m_windowHeight, 1.0f);
			m_pRenderer->ImmediateTextureCoordinate(0.0f, 1.0f);
			m_pRenderer->ImmediateVertex(0.0f, (float)m_windowHeight, 1.0f);
		m_pRenderer->DisableImmediateMode();

		m_pRenderer->EmptyTextureIndex(0);

		m_pRenderer->EndGLSLShader(m_blurHorizontalShader);
		m_pRenderer->StopRenderingToFrameBuffer(m_secondPassFullscreenBuffer);
	m_pRenderer->PopMatrix();
}
Exemplo n.º 9
0
static void panel_draw_internal(panel *p, float x, float y, float width, float height) {    
    glUseProgramObjectARB(p->shader_program);
    glUniform4fARB(glGetUniformLocationARB(p->shader_program, "extents"), x, 1.0f-y-height, width, height);
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, p->font);

    glActiveTexture(GL_TEXTURE1);
    glBindTexture(GL_TEXTURE_2D, p->fg_tex);
    glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, p->width, p->height, GL_RGBA, GL_UNSIGNED_BYTE, p->foreground);

    glActiveTexture(GL_TEXTURE2);
    glBindTexture(GL_TEXTURE_2D, p->bg_tex);
    glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, p->width, p->height, GL_RGBA, GL_UNSIGNED_BYTE, p->background);

    glBindBufferARB(GL_ARRAY_BUFFER_ARB, p->vbo);

    glEnableClientState(GL_VERTEX_ARRAY);
    glVertexPointer(3, GL_FLOAT, 5*sizeof(GLfloat), (char*)0 + 0*sizeof(GLfloat));

    glEnableClientState(GL_TEXTURE_COORD_ARRAY);
    glTexCoordPointer(2, GL_FLOAT, 5*sizeof(GLfloat), (char*)0 + 3*sizeof(GLfloat));

    glDrawArrays(GL_TRIANGLES, 0, 6);
}
Exemplo n.º 10
0
void Shader::SetTexture(const std::string& name, const Image& texture)
{
    if (myShaderProgram)
    {
        EnsureGlContext();

        // Find the location of the variable in the shader
        int location = glGetUniformLocationARB(myShaderProgram, name.c_str());
        if (location == -1)
        {
            Err() << "Texture \"" << name << "\" not found in shader" << std::endl;
            return;
        }

        // Store the location -> texture mapping
        TextureTable::iterator it = myTextures.find(location);
        if (it == myTextures.end())
        {
            // New entry, make sure there are enough texture units
            GLint maxUnits;
            GLCheck(glGetIntegerv(GL_MAX_TEXTURE_COORDS_ARB, &maxUnits));
            if (myTextures.size() + 1 >= static_cast<std::size_t>(maxUnits))
            {
                Err() << "Impossible to use texture \"" << name << "\" for shader: all available texture units are used" << std::endl;
                return;
            }

            myTextures[location] = &texture;
        }
        else
        {
            // Location already used, just replace the texture
            it->second = &texture;
        }
    }
}
Exemplo n.º 11
0
Arquivo: Shader.cpp Projeto: BSkin/MTG
void Shader::setUniformMatrixf4(const std::string &variable, const glm::mat4 &value)
{
	const long matrixCount = 1; const bool shouldTranspose = GL_FALSE;
	if (shaderProgram != -1) 
		glUniformMatrix4fvARB (glGetUniformLocationARB (shaderProgram, variable.c_str ()), matrixCount, shouldTranspose, glm::value_ptr(value));
}
Exemplo n.º 12
0
void VoxGame::RenderDeferredLighting()
{
	// Render deferred lighting to light frame buffer
	m_pRenderer->PushMatrix();
		m_pRenderer->StartRenderingToFrameBuffer(m_lightingFrameBuffer);

		m_pRenderer->SetFrontFaceDirection(FrontFaceDirection_CW);
		m_pRenderer->EnableTransparency(BF_ONE, BF_ONE);
		m_pRenderer->DisableDepthTest();

		// Set the default projection mode
		m_pRenderer->SetProjectionMode(PM_PERSPECTIVE, m_defaultViewport);

		// Set the lookat camera
		m_pGameCamera->Look();

		m_pRenderer->PushMatrix();
			m_pRenderer->BeginGLSLShader(m_lightingShader);

			glShader* pLightShader = m_pRenderer->GetShader(m_lightingShader);
			unsigned NormalsID = glGetUniformLocationARB(pLightShader->GetProgramObject(), "normals");
			unsigned PositionssID = glGetUniformLocationARB(pLightShader->GetProgramObject(), "positions");
			unsigned DepthsID = glGetUniformLocationARB(pLightShader->GetProgramObject(), "depths");

			m_pRenderer->PrepareShaderTexture(0, NormalsID);
			m_pRenderer->BindRawTextureId(m_pRenderer->GetNormalTextureFromFrameBuffer(m_SSAOFrameBuffer));

			m_pRenderer->PrepareShaderTexture(1, PositionssID);
			m_pRenderer->BindRawTextureId(m_pRenderer->GetPositionTextureFromFrameBuffer(m_SSAOFrameBuffer));

			m_pRenderer->PrepareShaderTexture(2, DepthsID);
			m_pRenderer->BindRawTextureId(m_pRenderer->GetDepthTextureFromFrameBuffer(m_SSAOFrameBuffer));

			pLightShader->setUniform1i("screenWidth", m_windowWidth);
			pLightShader->setUniform1i("screenHeight", m_windowHeight);
			pLightShader->setUniform1f("nearZ", 0.01f);
			pLightShader->setUniform1f("farZ", 1000.0f);

			for (int i = 0; i < m_pLightingManager->GetNumLights(); i++)
			{
				DynamicLight* lpLight = m_pLightingManager->GetLight(i);
				float lightRadius = lpLight->m_radius;

				vec3 cameraPos = vec3(m_pGameCamera->GetPosition().x, m_pGameCamera->GetPosition().y, m_pGameCamera->GetPosition().z);
				float length = glm::distance(cameraPos, lpLight->m_position);
				if (length < lightRadius + 0.5f) // Small change to account for differences in circle render (with slices) and circle radius
				{
					m_pRenderer->SetCullMode(CM_BACK);
				}
				else
				{
					m_pRenderer->SetCullMode(CM_FRONT);
				}

				pLightShader->setUniform1f("radius", lightRadius);
				pLightShader->setUniform1f("diffuseScale", lpLight->m_diffuseScale);

				float r = lpLight->m_colour.GetRed();
				float g = lpLight->m_colour.GetGreen();
				float b = lpLight->m_colour.GetBlue();
				float a = lpLight->m_colour.GetAlpha();
				pLightShader->setUniform4f("diffuseLightColor", r, g, b, a);

				m_pRenderer->PushMatrix();
					m_pRenderer->SetRenderMode(RM_SOLID);
					m_pRenderer->TranslateWorldMatrix(lpLight->m_position.x, lpLight->m_position.y + 0.5f, lpLight->m_position.z);
					m_pRenderer->DrawSphere(lightRadius, 30, 30);
				m_pRenderer->PopMatrix();
			}

			m_pRenderer->EmptyTextureIndex(2);
			m_pRenderer->EmptyTextureIndex(1);
			m_pRenderer->EmptyTextureIndex(0);

			m_pRenderer->EndGLSLShader(m_lightingShader);

		m_pRenderer->PopMatrix();

		m_pRenderer->SetFrontFaceDirection(FrontFaceDirection_CCW);
		m_pRenderer->DisableTransparency();
		m_pRenderer->SetCullMode(CM_BACK);
		m_pRenderer->EnableDepthTest(DT_LESS);

		m_pRenderer->StopRenderingToFrameBuffer(m_lightingFrameBuffer);

	m_pRenderer->PopMatrix();
}
Exemplo n.º 13
0
void VoxGame::RenderSSAOTexture()
{
	m_pRenderer->PushMatrix();
		m_pRenderer->SetProjectionMode(PM_2D, m_defaultViewport);
		m_pRenderer->SetLookAtCamera(vec3(0.0f, 0.0f, 250.0f), vec3(0.0f, 0.0f, 0.0f), vec3(0.0f, 1.0f, 0.0f));

		if (m_multiSampling)
		{
			m_pRenderer->StartRenderingToFrameBuffer(m_FXAAFrameBuffer);
		}
		else if (m_blur)
		{
			m_pRenderer->StartRenderingToFrameBuffer(m_firstPassFullscreenBuffer);
		}

		// SSAO shader
		m_pRenderer->BeginGLSLShader(m_SSAOShader);
		glShader* pShader = m_pRenderer->GetShader(m_SSAOShader);

		unsigned int textureId0 = glGetUniformLocationARB(pShader->GetProgramObject(), "bgl_DepthTexture");
		m_pRenderer->PrepareShaderTexture(0, textureId0);
		m_pRenderer->BindRawTextureId(m_pRenderer->GetDepthTextureFromFrameBuffer(m_SSAOFrameBuffer));

		unsigned int textureId1 = glGetUniformLocationARB(pShader->GetProgramObject(), "bgl_RenderedTexture");
		m_pRenderer->PrepareShaderTexture(1, textureId1);
		m_pRenderer->BindRawTextureId(m_pRenderer->GetDiffuseTextureFromFrameBuffer(m_SSAOFrameBuffer));

		unsigned int textureId2 = glGetUniformLocationARB(pShader->GetProgramObject(), "light");
		m_pRenderer->PrepareShaderTexture(2, textureId2);
		m_pRenderer->BindRawTextureId(m_pRenderer->GetDiffuseTextureFromFrameBuffer(m_lightingFrameBuffer));

		unsigned int textureId3 = glGetUniformLocationARB(pShader->GetProgramObject(), "bgl_TransparentTexture");
		m_pRenderer->PrepareShaderTexture(3, textureId3);
		m_pRenderer->BindRawTextureId(m_pRenderer->GetDiffuseTextureFromFrameBuffer(m_transparencyFrameBuffer));

		unsigned int textureId4 = glGetUniformLocationARB(pShader->GetProgramObject(), "bgl_TransparentDepthTexture");
		m_pRenderer->PrepareShaderTexture(4, textureId4);
		m_pRenderer->BindRawTextureId(m_pRenderer->GetDepthTextureFromFrameBuffer(m_transparencyFrameBuffer));

		pShader->setUniform1i("screenWidth", m_windowWidth);
		pShader->setUniform1i("screenHeight", m_windowHeight);
		pShader->setUniform1f("nearZ", 0.01f);
		pShader->setUniform1f("farZ", 1000.0f);

		pShader->setUniform1f("samplingMultiplier", 0.5f);

		pShader->setUniform1i("lighting_enabled", m_dynamicLighting);
		pShader->setUniform1i("ssao_enabled", m_ssao);

		m_pRenderer->SetRenderMode(RM_TEXTURED);
		m_pRenderer->EnableImmediateMode(IM_QUADS);
			m_pRenderer->ImmediateTextureCoordinate(0.0f, 0.0f);
			m_pRenderer->ImmediateVertex(0.0f, 0.0f, 1.0f);
			m_pRenderer->ImmediateTextureCoordinate(1.0f, 0.0f);
			m_pRenderer->ImmediateVertex((float)m_windowWidth, 0.0f, 1.0f);
			m_pRenderer->ImmediateTextureCoordinate(1.0f, 1.0f);
			m_pRenderer->ImmediateVertex((float)m_windowWidth, (float)m_windowHeight, 1.0f);
			m_pRenderer->ImmediateTextureCoordinate(0.0f, 1.0f);
			m_pRenderer->ImmediateVertex(0.0f, (float)m_windowHeight, 1.0f);
		m_pRenderer->DisableImmediateMode();

		m_pRenderer->EmptyTextureIndex(4);
		m_pRenderer->EmptyTextureIndex(3);
		m_pRenderer->EmptyTextureIndex(2);
		m_pRenderer->EmptyTextureIndex(1);
		m_pRenderer->EmptyTextureIndex(0);

		m_pRenderer->EndGLSLShader(m_SSAOShader);

		if (m_multiSampling)
		{
			m_pRenderer->StopRenderingToFrameBuffer(m_FXAAFrameBuffer);
		}
		else if (m_blur)
		{
			m_pRenderer->StopRenderingToFrameBuffer(m_firstPassFullscreenBuffer);
		}
	m_pRenderer->PopMatrix();
}
Exemplo n.º 14
0
Arquivo: Shader.cpp Projeto: BSkin/MTG
void Shader::setUniformi1(const std::string &variable, long value) {
	if (shaderProgram != -1) 
		glUniform1iARB (glGetUniformLocationARB (shaderProgram, variable.c_str ()), value);
}
Exemplo n.º 15
0
void VoxGame::Render()
{
	if (m_pVoxWindow->GetMinimized())
	{
		// Don't call any render functions if minimized
		return;
	}

	glShader* pShader = NULL;

	// Begin rendering
	m_pRenderer->BeginScene(true, true, true);

		// Shadow rendering to the shadow frame buffer
		if (m_shadows)
		{
			RenderShadows();
		}

		// SSAO frame buffer rendering start
		if (m_deferredRendering)
		{
			m_pRenderer->StartRenderingToFrameBuffer(m_SSAOFrameBuffer);
		}

		// ---------------------------------------
		// Render 3d
		// ---------------------------------------
		m_pRenderer->PushMatrix();
			// Set the default projection mode
			m_pRenderer->SetProjectionMode(PM_PERSPECTIVE, m_defaultViewport);

			// Set back culling as default
			m_pRenderer->SetCullMode(CM_BACK);

			// Set default depth test
			m_pRenderer->EnableDepthTest(DT_LESS);

			// Set the lookat camera
			m_pGameCamera->Look();

			// Enable the lights
			m_pRenderer->PushMatrix();
				m_pRenderer->EnableLight(m_defaultLight, 0);
			m_pRenderer->PopMatrix();

			// Multisampling MSAA
			if (m_multiSampling)
			{
				m_pRenderer->EnableMultiSampling();
			}
			else
			{
				m_pRenderer->DisableMultiSampling();
			}

			// Render the lights (DEBUG)
			m_pRenderer->PushMatrix();
				m_pRenderer->SetCullMode(CM_BACK);
				m_pRenderer->SetRenderMode(RM_SOLID);
				m_pRenderer->RenderLight(m_defaultLight);
			m_pRenderer->PopMatrix();

			if (m_shadows)
			{
				m_pRenderer->BeginGLSLShader(m_shadowShader);

				pShader = m_pRenderer->GetShader(m_shadowShader);
				GLuint shadowMapUniform = glGetUniformLocationARB(pShader->GetProgramObject(), "ShadowMap");
				m_pRenderer->PrepareShaderTexture(7, shadowMapUniform);
				m_pRenderer->BindRawTextureId(m_pRenderer->GetDepthTextureFromFrameBuffer(m_shadowFrameBuffer));
				glUniform1iARB(glGetUniformLocationARB(pShader->GetProgramObject(), "renderShadow"), m_shadows);
				glUniform1iARB(glGetUniformLocationARB(pShader->GetProgramObject(), "alwaysShadow"), false);
			}
			else
			{
				m_pRenderer->BeginGLSLShader(m_defaultShader);
			}

			// Render world
			//RenderWorld();

			// Render the chunks
			m_pChunkManager->Render();

			// Render the player
			if (m_cameraMode == CameraMode_FirstPerson)
			{
				m_pPlayer->RenderFirstPerson();
			}
			else
			{
				m_pPlayer->Render();
			}

			// Render the block particles
			m_pBlockParticleManager->Render();

			if (m_shadows)
			{
				m_pRenderer->EndGLSLShader(m_shadowShader);
			}
			else
			{
				m_pRenderer->EndGLSLShader(m_defaultShader);
			}

			// Debug rendering
			if(m_debugRender)
			{
				m_pLightingManager->DebugRender();

				m_pBlockParticleManager->RenderDebug();

				m_pPlayer->RenderDebug();

				m_pChunkManager->RenderDebug();
			}
		m_pRenderer->PopMatrix();

		// Render the deferred lighting pass
		if (m_dynamicLighting)
		{
			RenderDeferredLighting();
		}

		// ---------------------------------------
		// Render 2d
		// ---------------------------------------
		m_pRenderer->PushMatrix();
		m_pRenderer->PopMatrix();

		// SSAO frame buffer rendering stop
		if (m_deferredRendering)
		{
			m_pRenderer->StopRenderingToFrameBuffer(m_SSAOFrameBuffer);
		}

		// ---------------------------------------
		// Render transparency
		// ---------------------------------------
		RenderTransparency();

		// Render the SSAO texture
		if (m_deferredRendering)
		{
			RenderSSAOTexture();

			if (m_multiSampling && m_fxaaShader != -1)
			{
				RenderFXAATexture();
			}

			if(m_blur)
			{
				RenderFirstPassFullScreen();
				RenderSecondPassFullScreen();
			}
		}

		// Disable multisampling for 2d gui and text
		m_pRenderer->DisableMultiSampling();

		// Render debug information and text
		RenderDebugInformation();

		// Render the chunks 2d
		if (m_debugRender)
		{
			//m_pChunkManager->Render2D(m_pGameCamera, m_defaultViewport, m_defaultFont);
		}

		// Render the GUI
		RenderGUI();

	// End rendering
	m_pRenderer->EndScene();


	// Pass render call to the window class, allow to swap buffers
	m_pVoxWindow->Render();
}
//--------------------------------------------------------------
void testApp::setup(){
	
	ofBackground(0, 0, 0);
	ofSetFrameRate(60);
	glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LEQUAL);
	
	ofDisableArbTex();
    neheTexture.loadImage("images/crate.gif");
	
	shader.loadShader("shaders/shader");
	
	
    glGenBuffersARB(2, &vboId[0]);
    
	
    //GET ATTRIBUTE AND UNIFORMS
	shader.setShaderActive(true);
	
	locationID[VERTEX_POSITION_ATTRIBUTE] = glGetAttribLocationARB(shader.shader, "aVertexPosition");
	locationID[TEXTURE_COORD_ATTRIBUTE] = glGetAttribLocationARB(shader.shader, "aTextureCoord");
	locationID[VERTEX_NORMAL_ATTRIBUTE] = glGetAttribLocationARB(shader.shader, "aVertexNormal");
    glEnableVertexAttribArray(locationID[VERTEX_POSITION_ATTRIBUTE]);
	glEnableVertexAttribArray(locationID[TEXTURE_COORD_ATTRIBUTE]);
	glEnableVertexAttribArray(locationID[VERTEX_NORMAL_ATTRIBUTE]);
	locationID[P_MATRIX_UNIFORM] = glGetUniformLocationARB(shader.shader, "uPMatrix");
	locationID[MV_MATRIX_UNIFORM] = glGetUniformLocationARB(shader.shader, "uMVMatrix");
	locationID[NORMAL_MATRIX_UNIFORM] = glGetUniformLocationARB(shader.shader, "uNMatrix");
	
	
	
	shader.setUniformVariable1i((char*)"uUseLighting", use_lighting=!use_lighting);
	
	shader.setUniformVariable3f((char*)"uAmbientColor",ambient_red_value=0.2,ambient_green_value=0.2,ambient_blue_value=0.2);
	
	lightDirection.set(0.0,0.0,1.0);
	shader.setUniformVariable3f((char*)"uLightingDirection", lightDirection.x,lightDirection.y,lightDirection.z);
	
   	shader.setUniformVariable3f((char*)"uDirectionalColor", direct_red_value=0.8,direct_green_value=0.8,direct_blue_value=0.8);
	
	shader.setShaderActive(false);
	
   
	//SQUARE BUFFER 	
	glBindBuffer(GL_ARRAY_BUFFER, vboId[0]);
    glBufferData(GL_ARRAY_BUFFER, sizeof(cubeVertexPosition)+sizeof(cubeVertexTextureCoord)+sizeof(cubeVertexNormal), 0, GL_STATIC_DRAW);
	glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(cubeVertexPosition), cubeVertexPosition);                            
	glBufferSubData(GL_ARRAY_BUFFER, sizeof(cubeVertexPosition), sizeof(cubeVertexTextureCoord), cubeVertexTextureCoord);
	glBufferSubData(GL_ARRAY_BUFFER, sizeof(cubeVertexPosition)+sizeof(cubeVertexTextureCoord), sizeof(cubeVertexNormal), cubeVertexNormal);
	
	//INDEX BUFFERS
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vboId[1]);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(cubeVertexIndices), cubeVertexIndices, GL_STATIC_DRAW);
	
	
	//SETUP ROTATION AND Z VARS
	z=-7;
	xSpeed=ySpeed=0;
	
	//KEYS
	of_key_backspace_pressed=false;
	of_key_page_up_pressed=false;
	of_key_page_down_pressed=false;
	of_key_left_pressed=false;
	of_key_right_pressed=false;
	of_key_up_pressed=false;
	of_key_down_pressed=false;
	
	verdana.loadFont("fonts/verdana.ttf",8, false, true);
	verdana.setLineHeight(14.0f);
	
	
	

	
}
Exemplo n.º 17
0
Arquivo: Shader.cpp Projeto: BSkin/MTG
void Shader::setUniformTexture(const std::string &variable, long textureUnit)
{
	if (shaderProgram != -1) 
		glUniform1iARB (glGetUniformLocationARB (shaderProgram, variable.c_str ()), textureUnit);
}
Exemplo n.º 18
0
void ofxShader::setUniformVariable3f (char * name, float value, float value2, float value3){
	if (bLoaded == true){
		glUniform3fARB(glGetUniformLocationARB(shader, name), value, value2, value3);
	}
}
Exemplo n.º 19
0
void ofxShader::setUniformVariable1i (char * name, int value){
	if (bLoaded == true){
		glUniform1iARB(glGetUniformLocationARB(shader, name), value);
	}
}
Exemplo n.º 20
0
bool InitializeApp()
{
  glClearColor(0, 0, 0, 1);
  glShadeModel(GL_SMOOTH);
  glEnable(GL_DEPTH_TEST);
  glEnable(GL_TEXTURE_2D);

  // Load texture.
  int width = 0, height = 0, comp = 0;
  unsigned char *image;
  image = LoadTGA("/home/aashish/tools/mywork/src.git/data/noise.tga", width, height, comp);

  glGenTextures(1, &_gRandomSampler);
  glBindTexture(GL_TEXTURE_2D, _gRandomSampler);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, width, height,
               0, GL_RGB, GL_UNSIGNED_BYTE, image);

   delete[] image;

  // Load shaders.
  if(!CreateGLSLShader("/home/aashish/tools/mywork/src.git/opengl/ssao_crytek/setRenderTargetsVs.glsl",
                      "/home/aashish/tools/mywork/src.git/opengl/ssao_crytek/setRenderTargetsPs.glsl",
                      _gSetRenderTargetShader))
    return false;

  if(!CreateGLSLShader("/home/aashish/tools/mywork/src.git/opengl/ssao_crytek/clearRenderTargetsVs.glsl",
                      "/home/aashish/tools/mywork/src.git/opengl/ssao_crytek/clearRenderTargetsPs.glsl",
                      _gClearRenderTargetShader))
    return false;

  if(!CreateGLSLShader("/home/aashish/tools/mywork/src.git/opengl/ssao_crytek/ssaoVs.glsl",
                      "/home/aashish/tools/mywork/src.git/opengl/ssao_crytek/ssaoPs.glsl",
                      _gSsaoShader))
   return false;


  if(!CreateGLSLShader("/home/aashish/tools/mywork/src.git/opengl/ssao_crytek/hBlurVs.glsl",
                      "/home/aashish/tools/mywork/src.git/opengl/ssao_crytek/hBlurPs.glsl",
                      _gHorizontalBlurShader))
  return false;

  if(!CreateGLSLShader("/home/aashish/tools/mywork/src.git/opengl/ssao_crytek/vBlurVs.glsl",
                       "/home/aashish/tools/mywork/src.git/opengl/ssao_crytek/vBlurPs.glsl",
                       _gVerticalBlurShader))
    return false;

  if(!CreateGLSLShader("/home/aashish/tools/mywork/src.git/opengl/ssao_crytek/renderingVs.glsl",
                       "/home/aashish/tools/mywork/src.git/opengl/ssao_crytek/renderingPs.glsl",
                        _gRenderShader))
    return false;

  // Bind our shader variables.
  _gOffset            = glGetUniformLocationARB(_gRenderShader, "offset");

  _gLight1Pos             = glGetUniformLocationARB(_gRenderShader, "light1Pos");
  _gLight1AmbientColor    = glGetUniformLocationARB(_gRenderShader, "light1AmbientColor");
  _gLight1DiffuseColor    = glGetUniformLocationARB(_gRenderShader, "light1DiffuseColor");
  _gLight1SpecularColor   = glGetUniformLocationARB(_gRenderShader, "light1SpecularColor");

  _gLight2Pos             = glGetUniformLocationARB(_gRenderShader, "light2Pos");
  _gLight2AmbientColor    = glGetUniformLocationARB(_gRenderShader, "light2AmbientColor");
  _gLight2DiffuseColor    = glGetUniformLocationARB(_gRenderShader, "light2DiffuseColor");
  _gLight2SpecularColor   = glGetUniformLocationARB(_gRenderShader, "light2SpecularColor");

  _gAmbientOcclusion  = glGetUniformLocationARB(_gRenderShader, "aos");
  _gSceneColors       = glGetUniformLocationARB(_gRenderShader, "colors");
  _gSceneDepths       = glGetUniformLocationARB(_gRenderShader, "depths");
  _gSceneNormals      = glGetUniformLocationARB(_gRenderShader, "normals");

  _gSsaoOffset        = glGetUniformLocationARB(_gSsaoShader, "offset");
  _gSsaoNormals       = glGetUniformLocationARB(_gSsaoShader, "normals");
  _gSsaoDepths        = glGetUniformLocationARB(_gSsaoShader, "depths");
  _gSsaoRandoms       = glGetUniformLocationARB(_gSsaoShader, "randoms");

  _gHorizontalBlurSceneSampler       = glGetUniformLocationARB(_gHorizontalBlurShader, "scene");
  _gHorizontalBlurSceneSamplerDepth  = glGetUniformLocationARB(_gHorizontalBlurShader, "depths");
  _gHorizontalBlurSceneSamplerNormal = glGetUniformLocationARB(_gHorizontalBlurShader, "normals");

  _gVerticalBlurSceneSampler       = glGetUniformLocationARB(_gVerticalBlurShader, "scene");
  _gVerticalBlurSceneDepthSampler  = glGetUniformLocationARB(_gVerticalBlurShader, "depths");
  _gVerticalBlurSceneNormalSampler = glGetUniformLocationARB(_gVerticalBlurShader, "normals");

  // Create frame buffer objects.
  if(_gSceneFbo.Create(WIDTH, HEIGHT) == false)
    return false;

  // Create frame buffer objects.
  if(_gSsaoFbo.Create(WIDTH, HEIGHT) == false)
    return false;

  // Create frame buffer objects.
  if(_gHorizontalBlurFbo.Create(WIDTH, HEIGHT) == false)
    return false;

  if(_gVerticalBlurFbo.Create(WIDTH, HEIGHT) == false)
    return false;

  if(_gModel.LoadOBJ("/home/aashish/tools/mywork/src.git/data/sponza.obj") == false)
    return false;

  return true;
}
Exemplo n.º 21
0
void Renderer::Init()
{
	//sanity check, make sure required extension are supported
	log_file << "Checking for presence of required GL extensions...";
	if(!GLEE_ARB_texture_non_power_of_two)
	{
		throw std::exception("ARB_texture_non_power_of_two NOT supported.");
	}
	if(!GLEE_ARB_shader_objects)
	{
		throw std::exception("ARB_shader_objects NOT supported.");
	}
	if(!GLEE_EXT_framebuffer_object)
	{
		throw std::exception("EXT_framebuffer_object NOT supported.");
	}
	log_file << "done." << std::endl;

	/////////////////////////
	//create fbo
	glGenFramebuffersEXT(1, &fbo);
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo);

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

	glGenTextures(2, input_texture);

	glBindTexture(GL_TEXTURE_2D, input_texture[0]);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F_ARB, WINDOW_WIDTH, WINDOW_HEIGHT, 0, GL_RGBA, GL_FLOAT, NULL);

	glBindTexture(GL_TEXTURE_2D, input_texture[1]);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F_ARB, WINDOW_WIDTH, WINDOW_HEIGHT, 0, GL_RGBA, GL_FLOAT, NULL);

	glBindTexture(GL_TEXTURE_2D, 0);

	glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, input_texture[0], 0);
	glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT1_EXT, GL_TEXTURE_2D, input_texture[1], 0);

	GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);

	if(status==GL_FRAMEBUFFER_COMPLETE_EXT)
	{
		log_file << "FBO successfully created." << std::endl;
	}
	else
	{
		log_file << "Create FBO failed." << std::endl;
	}
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);

	log_file << "OpenGL error state: " << gluErrorString(glGetError()) << std::endl;
	/////////////////////////

	////////////////////////////////
	//create shaders
	//pass1
	LoadShaders(program_pass1, "mandelbrot.vert", "mandelbrot_pass1.frag");

	//pass 2
	LoadShaders(program_pass2, "mandelbrot.vert", "mandelbrot_pass2.frag");
	glUseProgramObjectARB(program_pass2);
	uniform_iteration_location = glGetUniformLocationARB(program_pass2, "iteration");
	uniform_input_p2_location = glGetUniformLocationARB(program_pass2, "input");
	glUseProgramObjectARB(0);

	//pass 3
	LoadShaders(program_pass3, "mandelbrot.vert", "mandelbrot_pass3.frag");
	glUseProgramObjectARB(program_pass3);
	uniform_max_iterations_location = glGetUniformLocationARB(program_pass3, "max_iterations");
	uniform_input_p3_location = glGetUniformLocationARB(program_pass3, "input");
	uniform_iteration_scale_location = glGetUniformLocationARB(program_pass3, "iteration_scale");
	glUseProgramObjectARB(0);

	log_file << "OpenGL error state: " << gluErrorString(glGetError()) << std::endl;
	//////////////////////////////////////
}
Exemplo n.º 22
0
void
Butterfly::draw()
{
    // the position of the butterfly
    // used by the shader
    glUniform3fARB(glGetUniformLocationARB(shader->getPid(), "worldpos"), pos[0], pos[1], pos[2]);

    glDepthMask(GL_TRUE);
    glEnable(GL_DEPTH_TEST);

    // local frame
    float rot[16] =
    {
        binormal[0], binormal[1], binormal[2], 0,
        dir[0], dir[1], dir[2], 0,
        normal[0], normal[1], normal[2], 0,
        pos[0], pos[1], pos[2], 1
    };
    glPushMatrix();
    glMultMatrixf(rot);
//	fprintf(stdout, "%f, %f, %f\n", pos[0], pos[1], pos[2]);

    for(int j=0; j<NUM_OBJS; j++)
    {
        glPushMatrix();
        float tmp = fabs(wing_cnt)-wing_angle;
        if(j<(NUM_OBJS>>1)) glRotatef(tmp, 0, 1, 0);
        else glRotatef(-tmp, 0, 1, 0);
        glScalef(size, size, size);

        // thickness/bump mapping texture
        glActiveTexture(GL_TEXTURE0);
        tex[(j*2)%NUM_TEXTURES].bind();
        // backface texture
        glActiveTexture(GL_TEXTURE1);
        tex[(j*2+1)%NUM_TEXTURES].bind();

//		if(j%2==0)
//		{
//			glEnable (GL_POLYGON_OFFSET_FILL);
//			glPolygonOffset (1., 1.);
//		}

        glBegin(GL_TRIANGLES);
        for(int i=0; i<geom[j].numFacets*3; i++)
        {
            glNormal3fv(geom[j].normals[geom[j].normalIdx[i]]);
            glMultiTexCoord2fv(GL_TEXTURE0, geom[j].texcoords[geom[j].texcoordIdx[i]]);
            glVertex3fv(geom[j].verts[geom[j].vertIdx[i]]);
        }
        glEnd();

//		if(j%2==0) glDisable (GL_POLYGON_OFFSET_FILL);

        glActiveTexture(GL_TEXTURE0);
        tex[(j*2)%NUM_TEXTURES].unbind();
        glActiveTexture(GL_TEXTURE1);
        tex[(j*2+1)%NUM_TEXTURES].unbind();

        glPopMatrix();

    }
Exemplo n.º 23
0
void ofxShader::setUniformVariable4fv (char * name, int count, float * value){
	if (bLoaded == true){
		glUniform4fvARB(glGetUniformLocationARB(shader, name), count, value);
	}
}
Exemplo n.º 24
0
int sageDisplay::updateScreen(dispSharedData *shared, bool barrierFlag)
{
   context->clearScreen();

   for (int i=0; i<tileNum; i++)   {
      sageRect tileRect = configStruct.tileRect[i];
      tileRect.updateBoundary();
      
      int tileX = (i % configStruct.dimX) * configStruct.width;
      int tileY = (i / configStruct.dimX) * configStruct.height;
      tileRect.x = tileX;
      tileRect.y = tileY;

      context->setupViewport(i, tileRect);

      drawObj.preDraw(tileRect);
      glMatrixMode(GL_PROJECTION);
      glLoadIdentity();
      glOrtho(tileRect.left, tileRect.right, tileRect.bottom, tileRect.top, 0, 100);
      glMatrixMode(GL_MODELVIEW);
      for (int j=0; j<noOfMontages[i]; j++) {
         sageMontage *mon = montages[i][j];

         if (!mon)
            continue;
            
         if (!mon->visible) 
            continue;
            
         //if (!mon->isValidTexCoord()) {
         //sage::printLog("sageDisplay::updateScreen : montage %d of tile %d doesn't have valid texture coordinates", mon->id, i);
         //continue;
         //}
         
         if (mon->pixelType == PIXFMT_YUV) {
#if defined(GLSL_YUV)
            glDisable(GL_TEXTURE_2D);
            glEnable(GL_TEXTURE_RECTANGLE_ARB);
            glBindTexture(GL_TEXTURE_RECTANGLE_ARB, mon->texHandle);
            glUseProgramObjectARB(PHandle);
            glActiveTexture(GL_TEXTURE0);
            int h=glGetUniformLocationARB(PHandle,"yuvtex");
            glUniform1iARB(h,0);  /* Bind yuvtex to texture unit 0 */
            glBindTexture(GL_TEXTURE_RECTANGLE_ARB,mon->texHandle);
#else
            glBindTexture(GL_TEXTURE_2D, mon->texHandle);
#endif
         }
         else {
            glBindTexture(GL_TEXTURE_2D, mon->texHandle);
         }
         
         //GLenum error = glGetError();
         //gluGetErrorString( error ) ) );

         float depth = -mon->depth;
         glBegin(GL_QUADS);
            float texX, texY;
            mon->texCoord.genTexCoord(LOWER_LEFT, texX, texY);
            //   std::cerr << "LL " << texX << " , " << texY << " , " ;
            glTexCoord2f(texX, texY);
            glVertex3f(mon->left, mon->bottom, depth);
				//std::cout << " drawing... " << mon->left <<  " " << mon->bottom << " " << depth << std::endl;

            mon->texCoord.genTexCoord(LOWER_RIGHT, texX, texY);
            //   std::cerr << "LR " << texX << " , " << texY << " , " ;
            glTexCoord2f(texX, texY);
            glVertex3f(mon->right, mon->bottom, depth);

            mon->texCoord.genTexCoord(UPPER_RIGHT, texX, texY);
            //   std::cerr << "UR " << texX << " , " << texY << " , " ;
            
            glTexCoord2f(texX, texY);
            glVertex3f(mon->right, mon->top, depth);
            
            mon->texCoord.genTexCoord(UPPER_LEFT, texX, texY);
            //   std::cerr << "UL " << texX << " , " << texY << std::endl;
   
            glTexCoord2f(texX, texY);
            glVertex3f(mon->left, mon->top, depth);
         glEnd();

         if (mon->pixelType == PIXFMT_YUV) {
#if defined(GLSL_YUV)
            glUseProgramObjectARB(0);
            glDisable(GL_TEXTURE_RECTANGLE_ARB);
            glEnable(GL_TEXTURE_2D);
#endif
         }

      }
      drawObj.interDraw(tileRect);
      drawObj.postDraw(tileRect);

      context->refreshTile(i);
   }   
   
   //gettimeofday(&tve,NULL);   
  
   //double e = ((double)tve.tv_sec + 0.000001*(double)tve.tv_usec) - ((double)tvs.tv_sec + 0.000001*(double)tvs.tv_usec);
   //printf("%.9f elapsed\n", e); 
   //context->refreshScreen();
   
      /** BARRIER **/

   if ( barrierFlag ) {
	   shared->syncClientObj->sendRefreshBarrier(shared->nodeID);
	   //printf("node %d sent to barrier\n", shared->nodeID);
	   shared->syncClientObj->recvRefreshBarrier(false); // blocking (set true for nonblock)
	   //printf("node %d recved frm barrier\n", shared->nodeID);

   }

#ifdef DELAY_COMPENSATION
   if ( shared ) {
	   gettimeofday(&shared->localT, NULL); // my time

	   //fprintf(stderr,"SM sent %ld,%ld\n", shared->syncMasterT.tv_sec, shared->syncMasterT.tv_usec);
	   //fprintf(stderr,"SDM%d is %ld,%ld\n", shared->nodeID, shared->localT.tv_sec, shared->localT.tv_usec);
	   
	   double A = (double)shared->syncMasterT.tv_sec + 0.000001*(double)shared->syncMasterT.tv_usec;
	   A = A + ((double)shared->deltaT * 0.000001);
	   double B = (double)shared->localT.tv_sec + 0.000001*(double)shared->localT.tv_usec;
	   double wait = A - B;
	   wait *= 1000000.0;
	   
	   int llBusyWait = (int)wait;
	   if (  llBusyWait > 0 ) {
	     __usecDelay_RDTSC( llBusyWait );
	   }

	   //printf("SDM %d: %.6f msec waited\n", shared->nodeID, elapsed*1000.0);
   }
#endif

   context->refreshScreen();  // actual swapBuffer occurs in here at displayConext's instance
   dirty = false;
   
   return 0;
}
Exemplo n.º 25
0
Arquivo: ui.c Projeto: zbanks/radiance
static void ui_render(bool select) {
    GLint location;
    GLenum e;

    // Render strip indicators
    switch(strip_indicator) {
        case STRIPS_SOLID:
        case STRIPS_COLORED:
            glLoadIdentity();
            glViewport(0, 0, config.pattern.master_width, config.pattern.master_height);
            glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, strip_fb);
            glUseProgramObjectARB(strip_shader);

            location = glGetUniformLocationARB(strip_shader, "iPreview");
            glUniform1iARB(location, 0);
            location = glGetUniformLocationARB(strip_shader, "iResolution");
            glUniform2fARB(location, config.pattern.master_width, config.pattern.master_height);
            location = glGetUniformLocationARB(strip_shader, "iIndicator");
            glUniform1iARB(location, strip_indicator);

            glActiveTexture(GL_TEXTURE0);
            glBindTexture(GL_TEXTURE_2D, crossfader.tex_output);

            glClear(GL_COLOR_BUFFER_BIT);
            glBegin(GL_QUADS);
            for(struct output_device * d = output_device_head; d != NULL; d = d->next) {
#ifdef SOLID_LINE_INDICATOR
                bool first = true;
                double x;
                double y;
                for(struct output_vertex * v = d->vertex_head; v != NULL; v = v->next) {
                    if(!first) {
                        double dx = v->x - x;
                        double dy = -v->y - y;
                        double dl = hypot(dx, dy);
                        dx = config.ui.strip_thickness * dx / dl;
                        dy = config.ui.strip_thickness * dy / dl;
                        glVertex2d(x + dy, y - dx);
                        glVertex2d(v->x + dy, -v->y - dx);
                        glVertex2d(v->x - dy, -v->y + dx);
                        glVertex2d(x - dy, y + dx);
                    } else {
                        first = false;
                    }
                    x = v->x;
                    y = -v->y;
                }
#else // PIXEL INDICATOR
                // Maybe this is horrendously slow because it has to draw a quad for every output pixel? 
                // It looks cool though
                for (size_t i = 0; i < d->pixels.length; i++) {
                    double x = d->pixels.xs[i];
                    double y = d->pixels.ys[i];
                    double dx = config.ui.point_thickness;
                    double dy = config.ui.point_thickness;
                    glVertex2d(x + dx, y);
                    glVertex2d(x, y + dy);
                    glVertex2d(x - dx, y);
                    glVertex2d(x, y - dy);
                }
#endif
            }
            glEnd();
            break;
        default:
        case STRIPS_NONE:
            break;
    }

    // Render the patterns
    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, pat_fb);

    int pw = config.ui.pattern_width;
    int ph = config.ui.pattern_height;
    glUseProgramObjectARB(pat_shader);
    location = glGetUniformLocationARB(pat_shader, "iResolution");
    glUniform2fARB(location, pw, ph);
    glUseProgramObjectARB(pat_shader);
    location = glGetUniformLocationARB(pat_shader, "iSelection");
    glUniform1iARB(location, select);
    location = glGetUniformLocationARB(pat_shader, "iPreview");
    glUniform1iARB(location, 0);
    location = glGetUniformLocationARB(pat_shader, "iName");
    glUniform1iARB(location, 1);
    GLint pattern_index = glGetUniformLocationARB(pat_shader, "iPatternIndex");
    GLint pattern_intensity = glGetUniformLocationARB(pat_shader, "iIntensity");
    GLint name_resolution = glGetUniformLocationARB(pat_shader, "iNameResolution");

    glLoadIdentity();
    gluOrtho2D(0, pw, 0, ph);
    glViewport(0, 0, pw, ph);

    for(int i = 0; i < config.ui.n_patterns; i++) {
        struct pattern * p = deck[map_deck[i]].pattern[map_pattern[i]];
        if(p != NULL) {
            glActiveTexture(GL_TEXTURE0);
            glBindTexture(GL_TEXTURE_2D, p->tex_output);
            glActiveTexture(GL_TEXTURE1);
            SDL_GL_BindTexture(pattern_name_textures[i], NULL, NULL);
            glUniform1iARB(pattern_index, i);
            glUniform1fARB(pattern_intensity, p->intensity);
            glUniform2fARB(name_resolution, pattern_name_width[i], pattern_name_height[i]);
            glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, pattern_textures[i], 0);
            glClear(GL_COLOR_BUFFER_BIT);
            fill(pw, ph);
        }
    }

    // Render the crossfader
    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, crossfader_fb);

    int cw = config.ui.crossfader_width;
    int ch = config.ui.crossfader_height;
    glUseProgramObjectARB(crossfader_shader);
    location = glGetUniformLocationARB(crossfader_shader, "iResolution");
    glUniform2fARB(location, cw, ch);
    location = glGetUniformLocationARB(crossfader_shader, "iSelection");
    glUniform1iARB(location, select);
    location = glGetUniformLocationARB(crossfader_shader, "iPreview");
    glUniform1iARB(location, 0);
    location = glGetUniformLocationARB(crossfader_shader, "iStrips");
    glUniform1iARB(location, 1);
    location = glGetUniformLocationARB(crossfader_shader, "iIntensity");
    glUniform1fARB(location, crossfader.position);
    location = glGetUniformLocationARB(crossfader_shader, "iIndicator");
    glUniform1iARB(location, strip_indicator);

    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, crossfader.tex_output);

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

    glLoadIdentity();
    gluOrtho2D(0, cw, 0, ch);
    glViewport(0, 0, cw, ch);
    glClear(GL_COLOR_BUFFER_BIT);
    fill(cw, ch);

    int sw = 0;
    int sh = 0;
    int vw = 0;
    int vh = 0;
    if(!select) {
        analyze_render(tex_spectrum_data, tex_waveform_data, tex_waveform_beats_data);

        // Render the spectrum
        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, spectrum_fb);

        sw = config.ui.spectrum_width;
        sh = config.ui.spectrum_height;
        glUseProgramObjectARB(spectrum_shader);
        location = glGetUniformLocationARB(spectrum_shader, "iResolution");
        glUniform2fARB(location, sw, sh);
        location = glGetUniformLocationARB(spectrum_shader, "iBins");
        glUniform1iARB(location, config.audio.spectrum_bins);
        location = glGetUniformLocationARB(spectrum_shader, "iSpectrum");
        glUniform1iARB(location, 0);
        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_1D, tex_spectrum_data);

        glLoadIdentity();
        gluOrtho2D(0, sw, 0, sh);
        glViewport(0, 0, sw, sh);
        glClear(GL_COLOR_BUFFER_BIT);
        fill(sw, sh);

        // Render the waveform
        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, waveform_fb);

        vw = config.ui.waveform_width;
        vh = config.ui.waveform_height;
        glUseProgramObjectARB(waveform_shader);
        location = glGetUniformLocationARB(waveform_shader, "iResolution");
        glUniform2fARB(location, sw, sh);
        location = glGetUniformLocationARB(waveform_shader, "iLength");
        glUniform1iARB(location, config.audio.waveform_length);
        location = glGetUniformLocationARB(waveform_shader, "iWaveform");
        glUniform1iARB(location, 0);
        location = glGetUniformLocationARB(waveform_shader, "iBeats");
        glUniform1iARB(location, 1);
        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_1D, tex_waveform_data);
        glActiveTexture(GL_TEXTURE1);
        glBindTexture(GL_TEXTURE_1D, tex_waveform_beats_data);

        glLoadIdentity();
        gluOrtho2D(0, vw, 0, vh);
        glViewport(0, 0, vw, vh);
        glClear(GL_COLOR_BUFFER_BIT);
        fill(vw, vh);
    }

    // Render to screen (or select fb)
    if(select) {
        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, select_fb);
    } else {
        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
    }

    glLoadIdentity();
    gluOrtho2D(0, ww, 0, wh);
    glViewport(0, 0, ww, wh);

    glClear(GL_COLOR_BUFFER_BIT);

    glUseProgramObjectARB(main_shader);

    location = glGetUniformLocationARB(main_shader, "iResolution");
    glUniform2fARB(location, ww, wh);
    location = glGetUniformLocationARB(main_shader, "iSelection");
    glUniform1iARB(location, select);
    location = glGetUniformLocationARB(main_shader, "iSelected");
    glUniform1iARB(location, selected);
    location = glGetUniformLocationARB(main_shader, "iLeftDeckSelector");
    glUniform1iARB(location, left_deck_selector);
    location = glGetUniformLocationARB(main_shader, "iRightDeckSelector");
    glUniform1iARB(location, right_deck_selector);

    fill(ww, wh);

    // Blit UI elements on top
    glEnable(GL_BLEND);
    glUseProgramObjectARB(blit_shader);
    glActiveTexture(GL_TEXTURE0);
    location = glGetUniformLocationARB(blit_shader, "iTexture");
    glUniform1iARB(location, 0);

    for(int i = 0; i < config.ui.n_patterns; i++) {
        struct pattern * pattern = deck[map_deck[i]].pattern[map_pattern[i]];
        if(pattern != NULL) {
            glBindTexture(GL_TEXTURE_2D, pattern_textures[i]);
            blit(map_x[i], map_y[i], pw, ph);
        }
    }

    glBindTexture(GL_TEXTURE_2D, crossfader_texture);
    blit(config.ui.crossfader_x, config.ui.crossfader_y, cw, ch);

    if(!select) {
        glBindTexture(GL_TEXTURE_2D, spectrum_texture);
        blit(config.ui.spectrum_x, config.ui.spectrum_y, sw, sh);

        glBindTexture(GL_TEXTURE_2D, waveform_texture);
        blit(config.ui.waveform_x, config.ui.waveform_y, vw, vh);

        if(pat_entry) {
            for(int i = 0; i < config.ui.n_patterns; i++) {
                if(map_selection[i] == selected) {
                    glBindTexture(GL_TEXTURE_2D, pat_entry_texture);
                    blit(map_pe_x[i], map_pe_y[i], config.ui.pat_entry_width, config.ui.pat_entry_height);
                    break;
                }
            }
        }
    }

    glDisable(GL_BLEND);

    if((e = glGetError()) != GL_NO_ERROR) FAIL("OpenGL error: %s\n", gluErrorString(e));
}
Exemplo n.º 26
0
GLint moShaderGLSL::GetUniformID(moText uName)
{
    return glGetUniformLocationARB(m_ProgramObject, uName);
}
              glEnableClientState(GL_TEXTURE_COORD_ARRAY );
              glEnableClientState(GL_NORMAL_ARRAY);
              glEnableClientState(GL_VERTEX_ARRAY);
              glTexCoordPointer(3, GL_FLOAT, 0, (void*)(sizeof(marcFace_VERT) + sizeof(marcFace_NORM)));
              glNormalPointer(GL_FLOAT, 0, (void*)sizeof(marcFace_VERT));
              glVertexPointer(3, GL_FLOAT, 0, 0);

              //SPECULAR_textureID;
              //SPECULAR_textureID = glGetUniformLocationARB(marcFace_SHADER,"SpecularMap");
              //glUniform1iARB(SPECULAR_textureID, 2);
              //glActiveTextureARB(GL_TEXTURE2_ARB);
              //glBindTexture(GL_TEXTURE_2D,  specularMap[201]);

              DOT3_textureID;
              DOT3_textureID     = glGetUniformLocationARB(marcFace_SHADER,"NormalMap");
              glUniform1iARB(DOT3_textureID, 1);
              glActiveTextureARB(GL_TEXTURE1_ARB);
              glBindTexture(GL_TEXTURE_2D,  normalMap[201]);

              textureID;
              textureID     = glGetUniformLocationARB(marcFace_SHADER,"Texture1");
              glUniform1iARB(textureID, 0);
              glActiveTextureARB(GL_TEXTURE0_ARB);
              glBindTexture(GL_TEXTURE_2D, textureMap[201]);

              //glLightfv(GL_LIGHT0,GL_POSITION,lightPos_marcFace);
              //glLightf (GL_LIGHT0, GL_QUADRATIC_ATTENUATION, lightAttenuation_marcFace);

              glDrawArrays(GL_TRIANGLES, 0, 1761);
Exemplo n.º 28
0
int main(int argc, char **argv)
{
   float r = 0.5, g = 0.5, b = 1, ratio = 0;
   int dir = 1;
   ALLEGRO_DISPLAY *display;
   ALLEGRO_BITMAP *mysha;
   ALLEGRO_BITMAP *buffer;

   const char *tinter_shader_src[] = {
      "uniform sampler2D backBuffer;",
      "uniform float r;",
      "uniform float g;",
      "uniform float b;",
      "uniform float ratio;",
      "void main() {",
      "	vec4 color;",
      "	float avg, dr, dg, db;",
      "	color = texture2D(backBuffer, gl_TexCoord[0].st);",
      "	avg = (color.r + color.g + color.b) / 3.0;",
      "	dr = avg * r;",
      "	dg = avg * g;",
      "	db = avg * b;",
      "	color.r = color.r - (ratio * (color.r - dr));",
      "	color.g = color.g - (ratio * (color.g - dg));",
      "	color.b = color.b - (ratio * (color.b - db));",
      "	gl_FragColor = color;",
      "}"
   };
   const int TINTER_LEN = 18;
   double start;
   GLint loc;

   (void)argc;
   (void)argv;

   if (!al_init()) {
      abort_example("Could not init Allegro\n");
   }

   al_install_keyboard();
   al_init_image_addon();

   al_set_new_display_flags(ALLEGRO_OPENGL);
   display = al_create_display(320, 200);
   if (!display) {
      abort_example("Error creating display\n");
   }

   mysha = al_load_bitmap("data/mysha.pcx");
   if (!mysha) {
      abort_example("Could not load image.\n");
   }

   buffer = al_create_bitmap(320, 200);

   if (!al_have_opengl_extension("GL_EXT_framebuffer_object")
      && !al_have_opengl_extension("GL_ARB_fragment_shader")) {
      abort_example("Fragment shaders not supported.\n");
   }

   tinter_shader = glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB);

   glShaderSourceARB(tinter_shader, TINTER_LEN, tinter_shader_src, NULL);
   glCompileShaderARB(tinter_shader);
   tinter = glCreateProgramObjectARB();
   glAttachObjectARB(tinter, tinter_shader);
   glLinkProgramARB(tinter);
   loc = glGetUniformLocationARB(tinter, "backBuffer");
   glUniform1iARB(loc, al_get_opengl_texture(buffer));

   start = al_get_time();

   while (1) {
      double now, diff;
      ALLEGRO_KEYBOARD_STATE state;
      al_get_keyboard_state(&state);
      if (al_key_down(&state, ALLEGRO_KEY_ESCAPE)) {
         break;
      }
      now = al_get_time();
      diff = now - start;
      start = now;
      ratio += diff * 0.5 * dir;
      if (dir < 0 && ratio < 0) {
         ratio = 0;
         dir = -dir;
      }
      else if (dir > 0 && ratio > 1) {
         ratio = 1;
         dir = -dir;
      }

      al_set_target_bitmap(buffer);

      glUseProgramObjectARB(tinter);
      loc = glGetUniformLocationARB(tinter, "ratio");
      glUniform1fARB(loc, ratio);
      loc = glGetUniformLocationARB(tinter, "r");
      glUniform1fARB(loc, r);
      loc = glGetUniformLocationARB(tinter, "g");
      glUniform1fARB(loc, g);
      loc = glGetUniformLocationARB(tinter, "b");
      glUniform1fARB(loc, b);
      al_draw_bitmap(mysha, 0, 0, 0);
      glUseProgramObjectARB(0);

      al_set_target_backbuffer(display);
      al_draw_bitmap(buffer, 0, 0, 0);
      al_flip_display();
      al_rest(0.001);
   }

   glDetachObjectARB(tinter, tinter_shader);
   glDeleteObjectARB(tinter_shader);

   al_uninstall_system();

   return 0;
}
Exemplo n.º 29
0
void CWater::RenderWater(CVec3f cameraPos, CFloat elapsedTime )
{
	if( g_fogBlurPass )
	{
		glDisable( GL_CULL_FACE );
		glBegin( GL_QUADS );
		glVertex3f(m_sidePoint[0].x, m_sidePoint[0].y, m_sidePoint[0].z);
		glVertex3f(m_sidePoint[1].x, m_sidePoint[1].y, m_sidePoint[1].z);
		glVertex3f(m_sidePoint[2].x, m_sidePoint[2].y, m_sidePoint[2].z);
		glVertex3f(m_sidePoint[3].x, m_sidePoint[3].y, m_sidePoint[3].z);
		glEnd();
		glEnable( GL_CULL_FACE );
	}
	else
	{
		glDisable( GL_CULL_FACE );
 		// Turn on the first texture unit and bind the REFLECTION texture
		glActiveTexture(GL_TEXTURE0);
		glEnable(GL_TEXTURE_2D); 
		glBindTexture(GL_TEXTURE_2D, m_waterTexture[WATER_REFLECTION_ID]);

		// Turn on the second texture unit and bind the REFRACTION texture
		glActiveTexture(GL_TEXTURE1);
		glEnable(GL_TEXTURE_2D);
		glBindTexture(GL_TEXTURE_2D, m_waterTexture[WATER_REFRACTION_ID]);

		// Turn on the third texture unit and bind the NORMAL MAP texture
		glActiveTexture(GL_TEXTURE2);
		glEnable(GL_TEXTURE_2D); 
		glBindTexture(GL_TEXTURE_2D, m_normalMapImg->GetId() );

		// Turn on the fourth texture unit and bind the DUDV MAP texture
		glActiveTexture(GL_TEXTURE3);
		glEnable(GL_TEXTURE_2D);
		glBindTexture(GL_TEXTURE_2D, m_dudvMapImg->GetId() );

		// Turn on the fifth texture unit and bind the DEPTH texture
		glActiveTexture(GL_TEXTURE4);
		glEnable(GL_TEXTURE_2D); 
		glBindTexture(GL_TEXTURE_2D, m_waterTexture[WATER_DEPTH_ID]);

		// Set the variable "reflection" to correspond to the first texture unit
		GLint uniform = glGetUniformLocationARB(g_render.m_waterProgram, "reflection"); 
		glUniform1iARB(uniform, 0); //second paramter is the texture unit 

		// Set the variable "refraction" to correspond to the second texture unit
		uniform = glGetUniformLocationARB(g_render.m_waterProgram, "refraction");
		glUniform1iARB(uniform, 1); 

		// Set the variable "normalMap" to correspond to the third texture unit
		uniform = glGetUniformLocationARB(g_render.m_waterProgram, "normalMap");
		glUniform1iARB(uniform, 2);

		// Set the variable "dudvMap" to correspond to the fourth texture unit
		uniform = glGetUniformLocationARB(g_render.m_waterProgram, "dudvMap"); 
		glUniform1iARB(uniform, 3);

		// Set the variable "depthMap" to correspond to the fifth texture unit
		uniform = glGetUniformLocationARB(g_render.m_waterProgram, "depthMap");
		glUniform1iARB(uniform, 4); 

		// Give the variable "waterColor" a blue color
		uniform = glGetUniformLocationARB(g_render.m_waterProgram, "waterColor");
		glUniform4fARB(uniform, 0.1f, 0.2f, 0.3f, 1.0f); 

		// We don't use lighting, but we do need to calculate
		// the diffuse and specular lighting on the water to increase realism.
		// position the light so it's near the light in the sky box texture.
		CVec3f lightPos(m_fWaterLPos[0], m_fWaterLPos[1], m_fWaterLPos[2]);

		// Give the variable "lightPos" our hard coded light position
		uniform = glGetUniformLocationARB(g_render.m_waterProgram, "lightPos");
		glUniform4fARB(uniform, lightPos.x, lightPos.y, lightPos.z, 1.0f); 

		// Give the variable "cameraPos" our camera position
		uniform = glGetUniformLocationARB(g_render.m_waterProgram, "cameraPos");
		glUniform4fARB(uniform, cameraPos.x, cameraPos.y, cameraPos.z, 1.0f); 
	
		// Create a static variable for the movement of the water
		static float move = 0.0f;

		// Use this variable for the normal map and make it slower
		// than the refraction map's speed.  We want the refraction
		// map to be jittery, but not the normal map's waviness.
		float move2 = move * kNormalMapScale;

		// Set the refraction map's UV coordinates to our global g_WaterUV
		float refrUV = m_fWaterUV;

		// Set our normal map's UV scale and shrink it by kNormalMapScale
		float normalUV = m_fWaterUV * kNormalMapScale;

		// Move the water by our global speed
		move += m_fWaterSpeed * elapsedTime;

		glUseProgram( g_render.m_waterProgram );

	   // Draw our huge water quad
		glBegin(GL_QUADS);

		// The back left vertex for the water
		glMultiTexCoord2fARB(GL_TEXTURE0_ARB, 0.0f, m_fWaterUV);				// Reflection texture				
		glMultiTexCoord2fARB(GL_TEXTURE1_ARB, 0.0f, refrUV - move);			// Refraction texture
		glMultiTexCoord2fARB(GL_TEXTURE2_ARB, 0.0f, normalUV + move2);		// Normal map texture
		glMultiTexCoord2fARB(GL_TEXTURE3_ARB, 0, 0);						// DUDV map texture
		glMultiTexCoord2fARB(GL_TEXTURE4_ARB, 0, 0);						// Depth texture
		glVertex3f(m_sidePoint[0].x, m_sidePoint[0].y, m_sidePoint[0].z);

		// The front left vertex for the water
		glMultiTexCoord2fARB(GL_TEXTURE0_ARB, 0.0f, 0.0f);					// Reflection texture
		glMultiTexCoord2fARB(GL_TEXTURE1_ARB, 0.0f, 0.0f - move);			// Refraction texture
		glMultiTexCoord2fARB(GL_TEXTURE2_ARB, 0.0f, 0.0f + move2);			// Normal map texture
		glMultiTexCoord2fARB(GL_TEXTURE3_ARB, 0, 0);						// DUDV map texture
		glMultiTexCoord2fARB(GL_TEXTURE4_ARB, 0, 0);						// Depth texture
		glVertex3f(m_sidePoint[1].x, m_sidePoint[1].y, m_sidePoint[1].z);

		// The front right vertex for the water
		glMultiTexCoord2fARB(GL_TEXTURE0_ARB, m_fWaterUV, 0.0f);				// Reflection texture
		glMultiTexCoord2fARB(GL_TEXTURE1_ARB, refrUV, 0.0f - move);			// Refraction texture
		glMultiTexCoord2fARB(GL_TEXTURE2_ARB, normalUV, 0.0f + move2);		// Normal map texture
		glMultiTexCoord2fARB(GL_TEXTURE3_ARB, 0, 0);						// DUDV map texture
		glMultiTexCoord2fARB(GL_TEXTURE4_ARB, 0, 0);						// Depth texture
		glVertex3f(m_sidePoint[2].x, m_sidePoint[2].y, m_sidePoint[2].z);

		// The back right vertex for the water
		glMultiTexCoord2fARB(GL_TEXTURE0_ARB, m_fWaterUV, m_fWaterUV);		// Reflection texture
		glMultiTexCoord2fARB(GL_TEXTURE1_ARB, refrUV, refrUV - move);		// Refraction texture
		glMultiTexCoord2fARB(GL_TEXTURE2_ARB, normalUV, normalUV + move2);	// Normal map texture
		glMultiTexCoord2fARB(GL_TEXTURE3_ARB, 0, 0);						// DUDV map texture
		glMultiTexCoord2fARB(GL_TEXTURE4_ARB, 0, 0);						// Depth texture
		glVertex3f(m_sidePoint[3].x, m_sidePoint[3].y, m_sidePoint[3].z);

		glEnd();
		// Turn the fifth multi-texture pass off
		glActiveTexture(GL_TEXTURE4);		
		glBindTexture( GL_TEXTURE_2D, 0 );
		glDisable(GL_TEXTURE_2D);

		// Turn the fourth multi-texture pass off
		glActiveTexture(GL_TEXTURE3);		
		glBindTexture( GL_TEXTURE_2D, 0 );
		glDisable(GL_TEXTURE_2D);

		// Turn the third multi-texture pass off
		glActiveTexture(GL_TEXTURE2);
		glBindTexture( GL_TEXTURE_2D, 0 );
		glDisable(GL_TEXTURE_2D);

		// Turn the second multi-texture pass off
		glActiveTexture(GL_TEXTURE1);
		glBindTexture( GL_TEXTURE_2D, 0 );
		glDisable(GL_TEXTURE_2D);

		// Turn the first multi-texture pass off
		glActiveTexture(GL_TEXTURE0);	
		glBindTexture( GL_TEXTURE_2D, 0 );
		glDisable(GL_TEXTURE_2D);

		glEnable( GL_CULL_FACE );
		glDisable(GL_TEXTURE_2D);
	}

}
Exemplo n.º 30
0
int setup(void)
{
GLuint major, minor;
GLint success;
GLuint model_id;

	srand( (unsigned)time( NULL ) );

	// Make sure required functionality is available!
	if (!getGLversion( &major, &minor))
		return -1;

	if (major < 2)
	{
		printf("<!> OpenGL 2.0 or higher is required\n");
		return -1;
	}

	windowpos = IsExtSupported("GL_ARB_window_pos");

	// Make sure required functionality is available!
	if (!(IsExtSupported("GL_ARB_vertex_program")))
	{
		printf("<!> ARB vertex program extension not supported\n");
		return -1;
	}

	if (!(IsExtSupported("GL_ARB_fragment_program")))
	{
		printf("<!> ARB fragment program extension not supported\n");
		return -1;
	}

	if (!(IsExtSupported("GL_ARB_vertex_shader")))
	{
		printf("<!> ARB vertex shader extension not supported\n");
		return -1;
	}

	if (!(IsExtSupported("GL_ARB_fragment_shader")))
	{
		printf("<!> ARB fragment shader extension not supported\n");
		return -1;
	}

	if (!(IsExtSupported("GL_EXT_framebuffer_object")))
	{
		printf("<!> Framebuffer object extension not supported\n");
		return -1;
	}

	//Define extension prointers
	glGenFramebuffersEXT = (PFNGLGENFRAMEBUFFERSEXTPROC)glXGetProcAddressARB("glGenFramebuffersEXT");
	glBindFramebufferEXT = (PFNGLBINDFRAMEBUFFEREXTPROC)glXGetProcAddressARB("glBindFramebufferEXT");
	glFramebufferTexture2DEXT = (PFNGLFRAMEBUFFERTEXTURE2DEXTPROC)glXGetProcAddressARB("glFramebufferTexture2DEXT");
	glGenRenderbuffersEXT = (PFNGLGENRENDERBUFFERSEXTPROC)glXGetProcAddressARB("glGenRenderbuffersEXT");
	glBindRenderbufferEXT = (PFNGLBINDRENDERBUFFEREXTPROC)glXGetProcAddressARB("glBindRenderbufferEXT");
	glRenderbufferStorageEXT = (PFNGLRENDERBUFFERSTORAGEEXTPROC)glXGetProcAddressARB("glRenderbufferStorageEXT");
	glFramebufferRenderbufferEXT = (PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC)glXGetProcAddressARB("glFramebufferRenderbufferEXT");
	glDeleteFramebuffersEXT = (PFNGLDELETEFRAMEBUFFERSEXTPROC)glXGetProcAddressARB("glDeleteFramebuffersEXT");
	glDeleteRenderbuffersEXT = (PFNGLDELETERENDERBUFFERSEXTPROC)glXGetProcAddressARB("glDeleteRenderbuffersEXT");
	glCheckFramebufferStatusEXT = (PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC)glXGetProcAddressARB("glCheckFramebufferStatusEXT");

	if (	!glGenFramebuffersEXT || !glBindFramebufferEXT ||
		!glFramebufferTexture2DEXT || !glGenRenderbuffersEXT ||
		!glBindRenderbufferEXT || !glRenderbufferStorageEXT ||
		!glFramebufferRenderbufferEXT || !glDeleteFramebuffersEXT ||
		!glDeleteRenderbuffersEXT || !glCheckFramebufferStatusEXT )
	{
		printf("<!> Required extension not supported\n");
		return -1;
	}

	//Enable smooth shading
	glShadeModel(GL_SMOOTH);

	//Enable depth testing
	glEnable(GL_DEPTH_TEST);
	glPolygonOffset( scalePoly, biasPoly );

	//Enable backface culling
	glEnable(GL_CULL_FACE);
	glCullFace(GL_BACK);
	glFrontFace( GL_CW );

	//Background color (Ligth blue)
	glClearColor(0.0f, 0.4f, 0.8f, 1.0f);

	//Generate texture objects
	texture_id = (GLuint *)malloc( NUM_TEXTURES * sizeof(GLuint) );
	glGenTextures( NUM_TEXTURES, texture_id );

	// Enable Anisotropic filtering (for 2D textures only)
	if( enable_anisotropic )
	{
		glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &MaxAnisoLevel);
		if( AnisoLevel >  MaxAnisoLevel)
			AnisoLevel = MaxAnisoLevel;
		if( print_info )
			printf("<-> %.0fX anisotropic filtering enabled\n", AnisoLevel);
	}
	else
		AnisoLevel = 0.0f;

	// Enable FSAA
	if (enable_fsaa)
		glEnable(GL_MULTISAMPLE);

	//Load MD2 models and textures
	for (model_id = 0; model_id < NUM_MODELS; ++model_id)
	{
		// Load the .md2 model
		if ( (md2_model[model_id] = (MD2_MODEL_PTR)malloc(sizeof(MD2_MODEL))) == NULL)
		{
			printf("<!> Unable to allocate memory for MD2 model in %s\n", filename[3*model_id]);
			return -1;
		}

		if ( !LoadMD2(md2_model[model_id], filename[3*model_id]) )
		{
			printf("<!> Unable to load MD2 model from %s\n", filename[3*model_id]);
			return -1;
		}
		if( print_info )
			printf("<-> Loaded MD2 model from \"%s\" for model #%d\n", filename[3*model_id], model_id);

		// Load texture from disk
		if ( !LoadImageFromDisk(md2_model[model_id]->skin, filename[3*model_id+1]) )
		{
			printf("<!> Unable to load texture from %s \n", filename[3*model_id+1]);
			return -1;
		}
		if( print_info )
			printf("<-> Loaded texture from \"%s\" for model #%d\n", filename[3*model_id+1], model_id);

		//Set up model texture parameters
		glBindTexture(GL_TEXTURE_2D, texture_id[2*model_id]);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

		glTexImage2D(	GL_TEXTURE_2D, 0, md2_model[model_id]->skin->components,
				md2_model[model_id]->skin->width, md2_model[model_id]->skin->height,
				0, md2_model[model_id]->skin->format, GL_UNSIGNED_BYTE,
				md2_model[model_id]->skin->data);

		// Load normal from disk
		if ( !LoadImageFromDisk(md2_model[model_id]->normal, filename[3*model_id+2]) )
		{
			printf("<!> Unable to load texture from %s \n", filename[3*model_id+2]);
			return -1;
		}
		if( print_info )
			printf("<-> Loaded texture from \"%s\" for model #%d\n", filename[3*model_id+2], model_id);

		//Set up model texture parameters
		glBindTexture(GL_TEXTURE_2D, texture_id[2*model_id+1]);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

		glTexImage2D(	GL_TEXTURE_2D, 0, md2_model[model_id]->normal->components,
				md2_model[model_id]->normal->width, md2_model[model_id]->normal->height,
				0, md2_model[model_id]->normal->format, GL_UNSIGNED_BYTE,
				md2_model[model_id]->normal->data);
	}

	// Load floor texture from disk
	floor_texture = (IMAGE_PTR)malloc(sizeof(IMAGE));
	floor_texture->data = NULL;
	if ( !LoadImageFromDisk(floor_texture, filename[3*NUM_MODELS]) )
	{
		printf("<!> Unable to load texture from %s\n", filename[3*NUM_MODELS]);
		return -1;
	}
	if( print_info )
		printf("<-> Loaded texture from \"%s\"\n", filename[3*NUM_MODELS]);
	
	//Set up floor texture parameters
	glBindTexture(GL_TEXTURE_2D, texture_id[NUM_TEXTURES-2]);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

	if (enable_anisotropic)
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, AnisoLevel);

	glTexImage2D(	GL_TEXTURE_2D, 0, floor_texture->components,
			floor_texture->width, floor_texture->height,
			0, floor_texture->format, GL_UNSIGNED_BYTE,
			floor_texture->data);

	if (floor_texture->data)
	{
		free(floor_texture->data);
		floor_texture->data = NULL;
	}

	// Load floor normal map from disk
	floor_texture = (IMAGE_PTR)malloc(sizeof(IMAGE));
	floor_texture->data = NULL;
	if ( !LoadImageFromDisk(floor_texture, filename[3*NUM_MODELS+1]) )
	{
		printf("<!> Unable to load texture from %s\n", filename[3*NUM_MODELS+1]);
		return -1;
	}

	if( print_info )
		printf("<-> Loaded texture from \"%s\"\n", filename[3*NUM_MODELS+1]);
	
	//Set up floor texture parameters
	glBindTexture(GL_TEXTURE_2D, texture_id[NUM_TEXTURES-1]);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

	if (enable_anisotropic)
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, AnisoLevel);

	glTexImage2D(	GL_TEXTURE_2D, 0, floor_texture->components,
			floor_texture->width, floor_texture->height,
			0, floor_texture->format, GL_UNSIGNED_BYTE,
			floor_texture->data);

	if (floor_texture->data)
	{
		free(floor_texture->data);
		floor_texture->data = NULL;
	}

	// Load and compile low-level shaders
	glGenProgramsARB(NUM_SHADERS, ids);
	if (!CompileShader(GL_VERTEX_PROGRAM_ARB,   ids[0], DATA_DIR "data/shaders/light.vp"))
		return -1;
	if (!CompileShader(GL_FRAGMENT_PROGRAM_ARB, ids[1], DATA_DIR "data/shaders/lightMasked.fp"))
		return -1;

	// Create program object and compile GLSL shaders
	progObj = glCreateProgramObjectARB();

	if (!CompileGLSLshaders(&progObj,
		DATA_DIR "data/shaders/bumpTBN_SH_VP.glsl",
		DATA_DIR "data/shaders/bumpTBN_SH_FP.glsl", GL_FALSE))
		return -1;

	// Retrieve uniform and attributes locations
	glUseProgramObjectARB(progObj);

	colorMap = glGetUniformLocationARB(progObj, "colorMap");
	bumpMap = glGetUniformLocationARB(progObj, "bumpMap");
	shadowMap = glGetUniformLocationARB(progObj, "shadowMap");
	tangent = glGetAttribLocation(progObj, "tangent");
	binormal = glGetAttribLocation(progObj, "binormal");

	for (model_id = 0; model_id < NUM_MODELS; ++model_id)
	{
		md2_model[model_id]->tangent = tangent;
		md2_model[model_id]->binormal = binormal;
	}

	// Set texture units
	glUniform1i(  colorMap, 0 );
	glUniform1i(   bumpMap, 1 );
	glUniform1i( shadowMap, 2 );

	//Validate shaders
	glValidateProgramARB(progObj);
	glGetObjectParameterivARB(progObj, GL_OBJECT_VALIDATE_STATUS_ARB, &success);
	if (!success)
	{
		GLbyte infoLog[MAX_INFO_LOG_SIZE];
		glGetInfoLogARB(progObj, MAX_INFO_LOG_SIZE, NULL, (char *)infoLog);
		printf("<!> Error in program validation\n");
		printf("Info log: %s\n", infoLog);
		return -1;
	}

	//Disable GLSL and enable low-level shaders
	glUseProgramObjectARB(0);
	glEnable(GL_VERTEX_PROGRAM_ARB);
	glEnable(GL_FRAGMENT_PROGRAM_ARB);

	glBindProgramARB(GL_VERTEX_PROGRAM_ARB,   ids[0]);
	glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, ids[1]);

	// Create FrameBuffer
	if (!CreateFB( shadow_sz, &FBO, &shadow_tx ))
		return -1;

	//Prebuild the display lists
	FList = glGenLists(1);
	glNewList(FList, GL_COMPILE);
		DrawGround();
	glEndList();

	//Init animations and kinematic state
	md2_model[0]->anim_state = ANIMATION_RUN;
	md2_model[0]->anim_command = ANIMATION_START;
	md2_model[0]->delta_rate = 30.f;
	md2_model[0]->position.x = 85.f;
	md2_model[0]->position.z = 0.f;
	md2_model[0]->rotation = 90.f;

	md2_model[1]->anim_state = ANIMATION_RUN;
	md2_model[1]->anim_command = ANIMATION_START;
	md2_model[1]->delta_rate = 30.f;
	md2_model[1]->position.x = 85.f;
	md2_model[1]->position.z = 0.f;
	md2_model[1]->rotation = 90.f;

	md2_model[2]->anim_state = ANIMATION_STANDING_IDLE;
	md2_model[2]->anim_command = ANIMATION_START;

	// Set initial camera position and orientation
	xCam = 0.0f;
	yCam = 70.0f;
	zCam = 200.0f;

	eCam = -0.35f;
	aCam = 0.0f;

	lCam = 0.0f;
	vCam = 0.0f;
	dCam = 0.0f;

	//Set initial light
	aLit = 0.0f;
	eLit = 0.75f;

	// Initialise timer
	gettimeofday(&tv, NULL);
	t0 = (double)tv.tv_sec + tv.tv_usec / 1000000.0f;
	t1 = t0;
	t2 = t0;

	return 0;
}