Beispiel #1
0
void MainApp::initializeGL()
{
    // initialize glew
    GLenum err = glewInit();
    if ( err != GLEW_OK )
        return reportError(QString::fromUtf8(reinterpret_cast<const char*>(glewGetErrorString(err))));
 
    // set some basic opengl flags
    glEnable(GL_DEPTH_TEST);  // Enables Depth Testing
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glDepthFunc(GL_LESS);     // The Type Of Depth Test To Do
    glShadeModel(GL_SMOOTH);  // Enables Smooth Color Shading
    glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);

    // load shader programs
    if ( !m_glProgramMaterial.loadAndLink("shaders/vshader.glsl", "shaders/fshader.glsl") )
        return reportError(QString::fromUtf8(m_glProgramMaterial.getLastError().c_str()));
    if ( !m_glProgramTexD.loadAndLink("shaders/vshaderTexD.glsl", "shaders/fshaderTexD.glsl") )
        return reportError(QString::fromUtf8(m_glProgramTexD.getLastError().c_str()));

    // set texture to sample from GL_TEXTURE0
    GLUniform::setUniform(m_glProgramTexD, "u_diffuseMap", INT, 0);

    // get the uniform locations TODO make this in a class
    GLuint uMatrices = glGetUniformBlockIndex(m_glProgramMaterial.getProgramIdx(), "Matrices");
    if ( uMatrices == GL_INVALID_INDEX )
        std::cout << "Warning: Unable to find uniform block Matrices" << std::endl;

    GLuint uLights = glGetUniformBlockIndex(m_glProgramMaterial.getProgramIdx(), "Lights");
    if ( uLights == GL_INVALID_INDEX )
        std::cout << "Warning: Unable to find uniform block Lights" << std::endl;

    GLuint uMaterial = glGetUniformBlockIndex(m_glProgramMaterial.getProgramIdx(), "Material");
    if ( uMaterial == GL_INVALID_INDEX )
        std::cout << "Warning: Unable to find uniform block Material" << std::endl;

    // bind uniform blocks to indices TODO make this in a class
    glUniformBlockBinding(m_glProgramMaterial.getProgramIdx(), uMatrices, UB_MATRICES);
    glUniformBlockBinding(m_glProgramMaterial.getProgramIdx(), uLights, UB_LIGHT);
    glUniformBlockBinding(m_glProgramMaterial.getProgramIdx(), uMaterial, UB_MATERIAL);
    
    // same for other program
    uMatrices = glGetUniformBlockIndex(m_glProgramTexD.getProgramIdx(), "Matrices");
    if ( uMatrices == GL_INVALID_INDEX )
        std::cout << "Warning: Unable to find uniform block Matrices" << std::endl;
    uLights = glGetUniformBlockIndex(m_glProgramTexD.getProgramIdx(), "Lights");
    if ( uLights == GL_INVALID_INDEX )
        std::cout << "Warning: Unable to find uniform block Lights" << std::endl;
    uMaterial = glGetUniformBlockIndex(m_glProgramTexD.getProgramIdx(), "Material");
    if ( uMaterial == GL_INVALID_INDEX )
        std::cout << "Warning: Unable to find uniform block Material" << std::endl;
 
    glUniformBlockBinding(m_glProgramTexD.getProgramIdx(), uMatrices, UB_MATRICES);
    glUniformBlockBinding(m_glProgramTexD.getProgramIdx(), uLights, UB_LIGHT);
    glUniformBlockBinding(m_glProgramTexD.getProgramIdx(), uMaterial, UB_MATERIAL);

    m_glUniformMatrixBuffer.generate(1);
    m_glUniformLightsBuffer.generate(1);
    m_glUniformMaterialBuffer.generate(1);

    m_glUniformMatrixBuffer.bind(GL_UNIFORM_BUFFER);
    m_glUniformMatrixBuffer.setEmpty(MAT_BUFFER_SIZE, GL_DYNAMIC_DRAW);
    m_glUniformLightsBuffer.bind(GL_UNIFORM_BUFFER);
    m_glUniformLightsBuffer.setEmpty(LIGHT_BUFFER_SIZE, GL_DYNAMIC_DRAW);
    m_glUniformMaterialBuffer.bind(GL_UNIFORM_BUFFER);
    m_glUniformMaterialBuffer.setEmpty(MATERIAL_BUFFER_SIZE, GL_DYNAMIC_DRAW);

    m_glUniformMatrixBuffer.bindBase(UB_MATRICES);
    m_glUniformLightsBuffer.bindBase(UB_LIGHT);
    m_glUniformMaterialBuffer.bindBase(UB_MATERIAL);
   
    GLBuffer::unbindBuffers(GL_UNIFORM_BUFFER);

    // initialize physics
    m_physics.init();

    // initialize table
    std::shared_ptr<Table> table = std::shared_ptr<Table>(new Table);
    if ( !table->init(m_physics, glm::vec3(0.0f, 0.0f, 0.0f)) )
        return reportError("Unable to load table");
    table->setUniforms(m_glUniformMaterialBuffer, MATERIALS);
    m_renderTargets.push_back(std::shared_ptr<iGLRenderable>(table));
    m_physicsTargets.push_back(std::shared_ptr<iPhysicsObject>(table));

    // initialize puck
    std::shared_ptr<Puck> puck = std::shared_ptr<Puck>(new Puck);
    if ( !puck->init(m_physics, glm::vec3(0.0f, 0.0f, 0.0f), 0.1f) )
        return reportError("Unable to load puck");
    puck->setUniforms(m_glUniformMaterialBuffer, MATERIALS);
    m_renderTargets.push_back(std::shared_ptr<iGLRenderable>(puck));
    m_physicsTargets.push_back(std::shared_ptr<iPhysicsObject>(puck));

    // TODO temporary just to show physics works
    //puck->setVelocity(glm::vec3(1.2f,0.0f,2.0f));

    // move the camera back and up
    m_camera[0].moveStraight(-3.0f);
    m_camera[0].moveHoriz(5.0f);
    m_camera[0].moveVert(2.0f);
    m_camera[0].rotateVert(-25.0f);
    m_camera[0].rotateHoriz(57.0f);
   
    m_camera[1].rotateHoriz(180.0);
    m_camera[1].moveStraight(-3.0f);
    m_camera[1].moveHoriz(5.0f);
    m_camera[1].moveVert(2.0f);
    m_camera[1].rotateVert(-25.0f);
    m_camera[1].rotateHoriz(57.0f);

    for ( int i = 0; i < LIGHT_ARRAY_SIZE; ++i )
        m_lights.addLight(LIGHT_DARK);
   
    // turn light #0 on player 1s position
    const glm::vec3 position0 = m_camera[0].getTranslation()[3].xyz();
    const LightInfo lightInfo0({
        position0 * -1.0f,
        glm::vec3(1.0f,1.0f,1.0f),
        glm::vec3(0.4f, 0.4f, 0.4f),
        glm::vec3(0.0f, 0.0f, 0.0f)});
    m_lights.setLightInfo(lightInfo0, 0);
    
    // turn light #1 on player 1s position
    const glm::vec3 position1 = m_camera[1].getTranslation()[3].xyz();
    const LightInfo lightInfo1({
        position1 * -1.0f,
        glm::vec3(1.0f,1.0f,1.0f),
        glm::vec3(0.4f, 0.4f, 0.4f),
        glm::vec3(0.0f, 0.0f, 0.0f)});
    m_lights.setLightInfo(lightInfo1, 1);

#ifdef GRAPHICS_DEBUG
    std::cout << "Loading Wireframe Debug Program" << std::endl;

    // load programs
    if ( !m_glProgramWireframe.loadAndLink("./shaders/debug/vshaderWireframe.glsl", "./shaders/debug/fshaderWireframe.glsl", "./shaders/debug/gshaderWireframe.glsl") )
        return reportError(QString::fromUtf8(m_glProgramWireframe.getLastError().c_str()));
    if ( !m_glProgramTexDWireframe.loadAndLink("./shaders/debug/vshaderTexDWireframe.glsl", "./shaders/debug/fshaderTexDWireframe.glsl", "./shaders/debug/gshaderTexDWireframe.glsl") )
        return reportError(QString::fromUtf8(m_glProgramTexDWireframe.getLastError().c_str()));

    // get and bind uniform block locations
    uMatrices = glGetUniformBlockIndex(m_glProgramWireframe.getProgramIdx(), "Matrices");
    if ( uMatrices == GL_INVALID_INDEX )
        std::cout << "Warning: Unable to find uniform block Matrices" << std::endl;
    uLights = glGetUniformBlockIndex(m_glProgramWireframe.getProgramIdx(), "Lights");
    if ( uLights == GL_INVALID_INDEX )
        std::cout << "Warning: Unable to find uniform block Lights" << std::endl;
    uMaterial = glGetUniformBlockIndex(m_glProgramWireframe.getProgramIdx(), "Material");
    if ( uMaterial == GL_INVALID_INDEX )
        std::cout << "Warning: Unable to find uniform block Material" << std::endl;
    
    glUniformBlockBinding(m_glProgramWireframe.getProgramIdx(), uMatrices, UB_MATRICES);
    glUniformBlockBinding(m_glProgramWireframe.getProgramIdx(), uLights, UB_LIGHT);
    glUniformBlockBinding(m_glProgramWireframe.getProgramIdx(), uMaterial, UB_MATERIAL);

    uMatrices = glGetUniformBlockIndex(m_glProgramTexDWireframe.getProgramIdx(), "Matrices");
    if ( uMatrices == GL_INVALID_INDEX )
        std::cout << "Warning: Unable to find uniform block Matrices" << std::endl;
    uLights = glGetUniformBlockIndex(m_glProgramTexDWireframe.getProgramIdx(), "Lights");
    if ( uLights == GL_INVALID_INDEX )
        std::cout << "Warning: Unable to find uniform block Lights" << std::endl;
    uMaterial = glGetUniformBlockIndex(m_glProgramTexDWireframe.getProgramIdx(), "Material");
    if ( uMaterial == GL_INVALID_INDEX )
        std::cout << "Warning: Unable to find uniform block Material" << std::endl;
    
    glUniformBlockBinding(m_glProgramTexDWireframe.getProgramIdx(), uMatrices, UB_MATRICES);
    glUniformBlockBinding(m_glProgramTexDWireframe.getProgramIdx(), uLights, UB_LIGHT);
    glUniformBlockBinding(m_glProgramTexDWireframe.getProgramIdx(), uMaterial, UB_MATERIAL);

    // find window size uniform for the wireframe 
    m_winSizeWireframe.init(m_glProgramWireframe, "u_windowSize", VEC2F);
    m_winSizeWireframe.loadData(glm::vec2(this->width()/4.0f, this->height()/2.0f));
    m_winSizeWireframe.set();
    m_winSizeTexDWireframe.init(m_glProgramTexDWireframe, "u_windowSize", VEC2F);
    m_winSizeTexDWireframe.loadData(glm::vec2(this->width()/4.0f, this->height()/2.0f));
    m_winSizeTexDWireframe.set();

    // set texture to sample from GL_TEXTURE0
    GLUniform diffuseMapWireframe;
    diffuseMapWireframe.init(m_glProgramTexDWireframe, "u_diffuseMap", INT);
    diffuseMapWireframe.loadData(0);
    diffuseMapWireframe.set();
#endif

#ifdef NORMALS_DEBUG
    std::cout << "Loading Normals Debug OpenGL Program" << std::endl;

    if ( !m_glProgramNormals.loadAndLink("./shaders/debug/vshaderNormals.glsl", "./shaders/debug/fshaderNormals.glsl", "./shaders/debug/gshaderNormals.glsl") )
        return reportError(QString::fromUtf8(m_glProgramNormals.getLastError().c_str()));

    // get and bind uniform block locations
    uMatrices = glGetUniformBlockIndex(m_glProgramNormals.getProgramIdx(), "Matrices");
    if ( uMatrices == GL_INVALID_INDEX )
        std::cout << "Warning: Unable to find uniform block Matrices" << std::endl;
    glUniformBlockBinding(m_glProgramNormals.getProgramIdx(), uMatrices, UB_MATRICES);

    // get the location projection matrix uniform
    m_uniformProjection.init(m_glProgramNormals, "u_projectionMatrix", MAT4F);
#endif
    
#ifdef PHYSICS_DEBUG
    std::cout << "Loading Physics Debug OpenGL Program" << std::endl;

    if ( !m_glProgramDebug.loadAndLink("./shaders/debug/vshaderPassthrough.glsl", "./shaders/debug/fshaderPassthrough.glsl") )
        return reportError(QString::fromUtf8(m_glProgramDebug.getLastError().c_str()));

    // get and bind uniform block locations
    uMatrices = glGetUniformBlockIndex(m_glProgramDebug.getProgramIdx(), "Matrices");
    if ( uMatrices == GL_INVALID_INDEX )
        std::cout << "Warning: Unable to find uniform block Matrices" << std::endl;
    glUniformBlockBinding(m_glProgramDebug.getProgramIdx(), uMatrices, UB_MATRICES);
  
    // tell physics world to use debug drawer
    m_physicsDebug = std::shared_ptr<PhysicsDebug>(new PhysicsDebug);
    m_physics.get()->setDebugDrawer(m_physicsDebug.get());
#endif
}
void UBOShaderInterface::SetBindingIndex(GLuint index)
{
	m_bufferBindIndex = index;

	glUniformBlockBinding(m_pShader->GetProgID(), m_blockIndex, m_bufferBindIndex);
}
PIGLIT_GL_TEST_CONFIG_END

void
piglit_init(int argc, char **argv)
{
	int i;
	GLuint prog;
	const char *source =
		"#extension GL_ARB_uniform_buffer_object : enable\n"
		"uniform a { float u1; };\n"
		"uniform b { float u2; };\n"
		"void main() {\n"
		"	gl_FragColor = vec4(u1 + u2);\n"
		"}\n";
	int blocks;
	int binding, max_bindings;
	bool pass = true;

	piglit_require_extension("GL_ARB_uniform_buffer_object");

	prog = piglit_build_simple_program(NULL, source);

	glGetProgramiv(prog, GL_ACTIVE_UNIFORM_BLOCKS, &blocks);
	assert(blocks == 2);

	for (i = 0; i < blocks; i++) {
		glGetActiveUniformBlockiv(prog, i, GL_UNIFORM_BLOCK_BINDING,
					  &binding);

		if (binding != 0) {
			fprintf(stderr,
				"Linked program should have binding[%d] = %d, "
				"saw %d\n",
				i, 0, binding);
			pass = false;
		}
	}

	for (i = 0; i < blocks; i++) {
		glUniformBlockBinding(prog, i, blocks - i);
	}

	for (i = 0; i < blocks; i++) {
		glGetActiveUniformBlockiv(prog, i, GL_UNIFORM_BLOCK_BINDING,
					  &binding);

		if (binding != blocks - i) {
			fprintf(stderr,
				"Updated binding[%d] to %d, but got %d\n",
				i, blocks - i, binding);
			pass = false;
		}
	}

	glLinkProgram(prog);

	for (i = 0; i < blocks; i++) {
		glGetActiveUniformBlockiv(prog, i, GL_UNIFORM_BLOCK_BINDING,
					  &binding);

		if (binding != 0) {
			fprintf(stderr,
				"Relinked program should have binding[%d] = %d, "
				"saw %d\n",
				i, 0, binding);
			pass = false;
		}
	}

	glUniformBlockBinding(prog, blocks, 0);
	pass = piglit_check_gl_error(GL_INVALID_VALUE) && pass;

	glGetIntegerv(GL_MAX_UNIFORM_BUFFER_BINDINGS, &max_bindings);
	glUniformBlockBinding(prog, 0, max_bindings);
	pass = piglit_check_gl_error(GL_INVALID_VALUE) && pass;

	glUniformBlockBinding(0xd0d0, 0, 0);
	pass = piglit_check_gl_error(GL_INVALID_VALUE) && pass;

	glDeleteProgram(prog);

	piglit_report_result(pass ? PIGLIT_PASS : PIGLIT_FAIL);
}
Beispiel #4
0
Renderer::Renderer(const int width, const int height) : width(width), height(height), mvp{}
{
    glDebugMessageCallback(gl_debug_callback, NULL);

    const int max_vertices {100};

    const GLbitfield flags {GL_MAP_WRITE_BIT |
                            GL_MAP_PERSISTENT_BIT |
                            GL_MAP_COHERENT_BIT};
    /* factor 3 comes from euler characteristic */
    const size_t vbo_size {max_vertices * 3 * sizeof(GLfloat)};
    const size_t ebo_size {max_vertices * sizeof(GLuint)};
    const size_t vbo_lines_size {10 * 4 * sizeof(GLfloat)};

    glGenBuffers(2, vbo);
    glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
    glBufferStorage(GL_ARRAY_BUFFER, vbo_size, NULL, flags);  
    vbo_mapped = glMapBufferRange(GL_ARRAY_BUFFER, 0, vbo_size, flags);
    glBindBuffer(GL_ARRAY_BUFFER, 0);

    glBindBuffer(GL_ARRAY_BUFFER, vbo[1]);
    glBufferStorage(GL_ARRAY_BUFFER, vbo_lines_size, NULL, flags);
    vbo_lines_mapped = glMapBufferRange(GL_ARRAY_BUFFER, 0, vbo_lines_size, flags);
    glBindBuffer(GL_ARRAY_BUFFER, 0);

    glGenBuffers(1, &ebo);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
    glBufferStorage(GL_ELEMENT_ARRAY_BUFFER, ebo_size, NULL, flags);
    ebo_mapped = glMapBufferRange(GL_ELEMENT_ARRAY_BUFFER, 0 , ebo_size, flags);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

    glGenVertexArrays(2, vao);
    glBindVertexArray(vao[0]);
    glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
    glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), 0);
    glEnableVertexAttribArray(0);
    glBindVertexArray(0);

    /* velocity VAO */
    glBindVertexArray(vao[1]);
    glBindBuffer(GL_ARRAY_BUFFER, vbo[1]);
    glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), 0);
    glEnableVertexAttribArray(0);
    glBindVertexArray(0);

    /* pass through shaders */
    const std::string vert_data = read_file("data/main.vert");
    const char *vert_data_ptr = vert_data.c_str();
    vert_prog[0] = glCreateShaderProgramv(GL_VERTEX_SHADER, 1, &vert_data_ptr);

    const std::string frag_data = read_file("data/main.frag");
    const char *frag_data_ptr = frag_data.c_str();
    frag_prog[0] = glCreateShaderProgramv(GL_FRAGMENT_SHADER, 1, &frag_data_ptr);

    glGenProgramPipelines(2, pipeline);
    
    glUseProgramStages(pipeline[0], GL_VERTEX_SHADER_BIT, vert_prog[0]);
    glUseProgramStages(pipeline[0], GL_FRAGMENT_SHADER_BIT, frag_prog[0]);

    /* debug arrows shaders */
    const std::string frag_velocity = read_file("data/velocity.frag");
    const char *frag_velocity_ptr = frag_velocity.c_str();
    frag_prog[1] = glCreateShaderProgramv(GL_FRAGMENT_SHADER, 1, &frag_velocity_ptr);

    glUseProgramStages(pipeline[1], GL_VERTEX_SHADER_BIT, vert_prog[0]);
    glUseProgramStages(pipeline[1], GL_FRAGMENT_SHADER_BIT, frag_prog[1]);
    

    /* set up uniforms */
    mvp.view = {20.0f / width, 0.0f, 0.0f, 0.0f,
                0.0f, 20.0f / height, 0.0f, 0.0f,
                0.0f, 0.0f, 1.0f, 0.0f,
                -1.0f, -1.0f, 0.0f, 1.0f}; 

    glGenBuffers(1, &ubo);
    glBindBuffer(GL_UNIFORM_BUFFER, ubo);
    glBufferStorage(GL_UNIFORM_BUFFER, sizeof(mvp), &mvp, GL_DYNAMIC_STORAGE_BIT);
    glBindBuffer(GL_UNIFORM_BUFFER, 0);
    
    glUniformBlockBinding(vert_prog[0], glGetUniformBlockIndex(vert_prog[0], "MVP"), 0);
    glBindBufferRange(GL_UNIFORM_BUFFER, 0, ubo, 0, sizeof(mvp));
}
JNIEXPORT void JNICALL Java_org_lwjgl_opengl_GL31_nglUniformBlockBinding(JNIEnv *env, jclass clazz, jint program, jint uniformBlockIndex, jint uniformBlockBinding, jlong function_pointer) {
	glUniformBlockBindingPROC glUniformBlockBinding = (glUniformBlockBindingPROC)((intptr_t)function_pointer);
	glUniformBlockBinding(program, uniformBlockIndex, uniformBlockBinding);
}
Beispiel #6
0
void
VSShaderLib::addBlocks() {

	int count, dataSize, actualLen, activeUnif, maxUniLength;
	int uniType, uniSize, uniOffset, uniMatStride, uniArrayStride, auxSize;
	char *name, *name2;

	UniformBlock block;

	glGetProgramiv(pProgram, GL_ACTIVE_UNIFORM_BLOCKS, &count);

	for (int i = 0; i < count; ++i) {
		// Get buffers name
		glGetActiveUniformBlockiv(pProgram, i, GL_UNIFORM_BLOCK_NAME_LENGTH, &actualLen);
		name = (char *)malloc(sizeof(char) * actualLen);
		glGetActiveUniformBlockName(pProgram, i, actualLen, NULL, name);

		bool newBlock=true;
		if (spBlocks.count(name)) {
			newBlock = false;
			block = spBlocks[name];
		}

		/*if (!spBlocks.count(name))*/ {
			// Get buffers size
			//block = spBlocks[name];
			glGetActiveUniformBlockiv(pProgram, i, GL_UNIFORM_BLOCK_DATA_SIZE, &dataSize);
			//printf("DataSize:%d\n", dataSize);

			if (newBlock) {
				glGenBuffers(1, &block.buffer);
				glBindBuffer(GL_UNIFORM_BUFFER, block.buffer);
				glBufferData(GL_UNIFORM_BUFFER, dataSize, NULL, GL_DYNAMIC_DRAW);
				glUniformBlockBinding(pProgram, i, spBlockCount);
				glBindBufferRange(GL_UNIFORM_BUFFER, spBlockCount, block.buffer, 0, dataSize);
			}
			else {
				glBindBuffer(GL_UNIFORM_BUFFER, block.buffer);
				glUniformBlockBinding(pProgram, i, block.bindingIndex);
			}
			glGetActiveUniformBlockiv(pProgram, i, GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS, &activeUnif);

			unsigned int *indices;
			indices = (unsigned int *)malloc(sizeof(unsigned int) * activeUnif);
			glGetActiveUniformBlockiv(pProgram, i, GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES, (int *)indices);
			
			glGetProgramiv(pProgram, GL_ACTIVE_UNIFORM_MAX_LENGTH, &maxUniLength);
			name2 = (char *)malloc(sizeof(char) * maxUniLength);

			for (int k = 0; k < activeUnif; ++k) {
		
				myBlockUniform bUni;

				glGetActiveUniformName(pProgram, indices[k], maxUniLength, &actualLen, name2);
				glGetActiveUniformsiv(pProgram, 1, &indices[k], GL_UNIFORM_TYPE, &uniType);
				glGetActiveUniformsiv(pProgram, 1, &indices[k], GL_UNIFORM_SIZE, &uniSize);
				glGetActiveUniformsiv(pProgram, 1, &indices[k], GL_UNIFORM_OFFSET, &uniOffset);
				glGetActiveUniformsiv(pProgram, 1, &indices[k], GL_UNIFORM_MATRIX_STRIDE, &uniMatStride);
				glGetActiveUniformsiv(pProgram, 1, &indices[k], GL_UNIFORM_ARRAY_STRIDE, &uniArrayStride);
			
				if (uniArrayStride > 0)
					auxSize = uniArrayStride * uniSize;
				
				else if (uniMatStride > 0) {

					switch(uniType) {
						case GL_FLOAT_MAT2:
						case GL_FLOAT_MAT2x3:
						case GL_FLOAT_MAT2x4:
						case GL_DOUBLE_MAT2:
						case GL_DOUBLE_MAT2x3:
						case GL_DOUBLE_MAT2x4:
							auxSize = 2 * uniMatStride;
							break;
						case GL_FLOAT_MAT3:
						case GL_FLOAT_MAT3x2:
						case GL_FLOAT_MAT3x4:
						case GL_DOUBLE_MAT3:
						case GL_DOUBLE_MAT3x2:
						case GL_DOUBLE_MAT3x4:
							auxSize = 3 * uniMatStride;
							break;
						case GL_FLOAT_MAT4:
						case GL_FLOAT_MAT4x2:
						case GL_FLOAT_MAT4x3:
						case GL_DOUBLE_MAT4:
						case GL_DOUBLE_MAT4x2:
						case GL_DOUBLE_MAT4x3:
							auxSize = 4 * uniMatStride;
							break;
					}
				}
				else
					auxSize = typeSize(uniType);

				bUni.offset = uniOffset;
				bUni.type = uniType;
				bUni.size = auxSize;
				bUni.arrayStride = uniArrayStride;

				block.uniformOffsets[name2] = bUni;


			}
			free(name2);
			if (newBlock) {
			block.size = dataSize;
			block.bindingIndex = spBlockCount;
			spBlockCount++;
			}
			spBlocks[name] = block;
		}
		//else
		//	glUniformBlockBinding(pProgram, i, spBlocks[name].bindingIndex);

	}

}
void Initialize()
{
	printf("Version Pilote OpenGL : %s\n", glGetString(GL_VERSION));
	printf("Type de GPU : %s\n", glGetString(GL_RENDERER));
	printf("Fabricant : %s\n", glGetString(GL_VENDOR));
	printf("Version GLSL : %s\n", glGetString(GL_SHADING_LANGUAGE_VERSION));
	int numExtensions;
	glGetIntegerv(GL_NUM_EXTENSIONS, &numExtensions);
	
	GLenum error = glewInit();
	if (error != GL_NO_ERROR) {
		// TODO
	}

#if LIST_EXTENSIONS
	for (int index = 0; index < numExtensions; ++index)
	{
		printf("Extension[%d] : %s\n", index, glGetStringi(GL_EXTENSIONS, index));
	}
#endif
	
#ifdef _WIN32
	// on coupe la synchro vertical pour voir l'effet du delta time
	wglSwapIntervalEXT(0);
#endif

	// render states par defaut
	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LESS);
	glEnable(GL_CULL_FACE);	

	// AntTweakBar
	
	TwInit(TW_OPENGL, NULL); // ou TW_OPENGL_CORE selon le cas de figure
	objTweakBar = TwNewBar("Multiple Point Lights");
	TwAddVarRW(objTweakBar, "Num Point Lights", TW_TYPE_UINT32, &g_NumPointLights, "");	
	TwAddButton(objTweakBar, "Quitter", &ExitCallbackTw, nullptr, "");
	
	// Objets OpenGL

	glGenBuffers(1, &g_Camera.UBO);
	glBindBuffer(GL_UNIFORM_BUFFER, g_Camera.UBO);
	glBufferData(GL_UNIFORM_BUFFER, sizeof(glm::mat4) * 2, nullptr, GL_STREAM_DRAW);
	

	glGenBuffers(1, &PointLight::UBO);
	glBindBuffer(GL_UNIFORM_BUFFER, PointLight::UBO);
	glBufferData(GL_UNIFORM_BUFFER, sizeof(PointLight) * MAX_POINT_LIGHTS, nullptr, GL_STREAM_DRAW);
	

	glGenBuffers(1, &Material::UBO);
	glBindBuffer(GL_UNIFORM_BUFFER, Material::UBO);
	glBufferData(GL_UNIFORM_BUFFER, sizeof(Material), &g_ShinyMaterial, GL_STATIC_DRAW);
	
	error = glGetError(); assert(error == GL_NO_ERROR);

	g_AmbientShader.LoadVertexShader("ambient.vs");
	g_AmbientShader.LoadFragmentShader("ambient.fs");
	g_AmbientShader.Create();
	auto program = g_AmbientShader.GetProgram();

	glBindBufferBase(GL_UNIFORM_BUFFER, 0, g_Camera.UBO);
	auto blockIndex = glGetUniformBlockIndex(program, "ViewProj");
	glUniformBlockBinding(program, blockIndex, 0);

	error = glGetError(); assert(error == GL_NO_ERROR);

	g_GBufferShader.LoadVertexShader("gbuffer.vs");
	g_GBufferShader.LoadFragmentShader("gbuffer.fs");
	g_GBufferShader.Create();
	program = g_GBufferShader.GetProgram();

	glBindBufferBase(GL_UNIFORM_BUFFER, 0, g_Camera.UBO); // deja bound
	blockIndex = glGetUniformBlockIndex(program, "ViewProj");
	glUniformBlockBinding(program, blockIndex, 0);

	glBindBufferBase(GL_UNIFORM_BUFFER, 1, PointLight::UBO);
	blockIndex = glGetUniformBlockIndex(program, "Lights");
	glUniformBlockBinding(program, blockIndex, 1);

	error = glGetError(); assert(error == GL_NO_ERROR);

	g_BlinnPhongShader.LoadVertexShader("blinnPhong.vs");
	g_BlinnPhongShader.LoadFragmentShader("blinnPhong.fs");
	g_BlinnPhongShader.Create();
	program = g_BlinnPhongShader.GetProgram();

	glBindBufferBase(GL_UNIFORM_BUFFER, 0, g_Camera.UBO); // deja bound
	blockIndex = glGetUniformBlockIndex(program, "ViewProj");
	glUniformBlockBinding(program, blockIndex, 0);

	glBindBufferBase(GL_UNIFORM_BUFFER, 2, Material::UBO);
	blockIndex = glGetUniformBlockIndex(program, "Material");
	glUniformBlockBinding(program, blockIndex, 2);

	// Setup
	error = glGetError(); assert(error == GL_NO_ERROR);

	previousTime = glutGet(GLUT_ELAPSED_TIME);

	LoadMesh(g_WallMesh, g_Room);

	LoadAndCreateTextureRGBA("wall_color_map.jpg", g_Walls.textures[Walls::gWallTexture]);
	glBindTexture(GL_TEXTURE_2D, g_Walls.textures[Walls::gWallTexture]);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	LoadAndCreateTextureRGBA("floor_color_map.jpg", g_Walls.textures[Walls::gFloorTexture]);
	glBindTexture(GL_TEXTURE_2D, g_Walls.textures[Walls::gFloorTexture]);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	LoadAndCreateTextureRGBA("ceiling_color_map.jpg", g_Walls.textures[Walls::gCeilingTexture]);
	glBindTexture(GL_TEXTURE_2D, g_Walls.textures[Walls::gCeilingTexture]);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

	const std::string inputFile = "sphere.obj";
	LoadOBJ(g_SphereMesh, inputFile);

	g_Spheres.resize(g_NumPointLights);
	for (uint32_t index = 0; index < g_NumPointLights; ++index)
	{
		g_Spheres[index].initialize(index);
	}

	g_GBuffer.CreateBuffer();

	error = glGetError(); assert(error == GL_NO_ERROR);
}
Beispiel #8
0
void CRenderer::UniformBlockBinding(GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding)
{
    glUniformBlockBinding(program, uniformBlockIndex, uniformBlockBinding);
    FC_CHECK_GL_ERROR_DEBUG();
}
Beispiel #9
0
// Create, compile and link program.
void ShaderProgram::createCompileLink()
{
	m_programName = glCreateProgram();
	for (std::map<GLenum, Shader *>::iterator it = m_shaders.begin(); it != m_shaders.end(); ++it)
	{
		(it->second)->createShader();
		glAttachShader(m_programName,(it->second)->shaderName());
	}

	checkOpenGLError("Error attaching shaders.");

	bool shaderCompilationFailed = false;
	for (std::map<GLenum, Shader *>::iterator it = m_shaders.begin(); it != m_shaders.end(); ++it)
	{
		GLint compileStatus = (it->second)->compile();
		if (compileStatus == GL_FALSE){
			shaderCompilationFailed = true;
			displayShaderCompileLog("Shader compilation failed", *(it->second));
		}
	}

	checkOpenGLError("Error compiling shaders.");
	
	// fail if some compilation failed
	if (shaderCompilationFailed)
		std::cout << "ERROR: Shader compilation failed" << std::endl;

	// "bind" vertex attribute channels
	for (auto& attrib : m_attribs){
		glBindAttribLocation(m_programName, attrib.second.index, attrib.second.name.c_str());
	}

	checkOpenGLError("Error binding attrib locations.");

	// link program and check for errors
	GLint linkResult = linkProgram();
	if (linkResult == GL_FALSE) {
		displayProgramLinkingLog("Shader Program linking failed");
	}

	// get uniform ids
	for (std::map<std::string, UniformData>::iterator it = m_uniforms.begin(); it != m_uniforms.end(); ++it) {
		const std::string &uniName = it->second.name;
		GLint loc = glGetUniformLocation(m_programName, uniName.c_str());
		it->second.id = loc;

		if (loc == -1) {
			std::cerr << "[Warning] Uniform not found: '" << uniName << "'" << std::endl;
		}
	}

	checkOpenGLError("Error getting unfiorm locations.");

	// bind uniform blocks (the buffer still needs to be assigned to the same bind point)
	for (std::map<std::string, UniformBlockData>::iterator it = m_uniformBlocks.begin(); it != m_uniformBlocks.end(); ++it) {
		const std::string &blockName = it->second.name;
		GLuint blockIndex = glGetUniformBlockIndex(m_programName, blockName.c_str());
		glUniformBlockBinding(m_programName, blockIndex, it->second.bindPoint);
	}

	checkOpenGLError("Error binding uniform blocks.");
}
Beispiel #10
0
void ShaderProgram::attachUniformBlock(string name, int index) const
{
	GLuint blockLocation = glGetUniformBlockIndex(handle, name.c_str());
	glUniformBlockBinding(handle, index, blockLocation);
}
Beispiel #11
0
int GLSL::enter()
{
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_RESIZABLE, GL_TRUE);

    GLFWwindow* window = glfwCreateWindow(screenWidth, screenHeight, "Advanced GLSL LearnOpenGL", nullptr, nullptr);
    glfwMakeContextCurrent(window);
    glfwSetKeyCallback(window, key_callback);
    glfwSetCursorPosCallback(window, mouse_callback);
    //glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);

    glewExperimental = GL_TRUE;
    glewInit();
    glViewport(0, 0, screenWidth, screenHeight);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_PROGRAM_POINT_SIZE);


    Shader shaderRed("../_ShaderSource/advanced/ubo.vs", "../_ShaderSource/advanced/uboRed.frag");
    Shader shaderGreen("../_ShaderSource/advanced/ubo.vs", "../_ShaderSource/advanced/uboGreen.frag");
    Shader shaderBlue("../_ShaderSource/advanced/ubo.vs", "../_ShaderSource/advanced/uboBlue.frag");
    Shader shaderYellow("../_ShaderSource/advanced/ubo.vs", "../_ShaderSource/advanced/uboYellow.frag");

     #pragma region "object_initialization"

    GLfloat cubeVertices[] = {
        -0.5f, -0.5f, -0.5f,
         0.5f,  0.5f, -0.5f,
         0.5f, -0.5f, -0.5f,
         0.5f,  0.5f, -0.5f,
        -0.5f, -0.5f, -0.5f,
        -0.5f,  0.5f, -0.5f,

        -0.5f, -0.5f,  0.5f,
         0.5f, -0.5f,  0.5f,
         0.5f,  0.5f,  0.5f,
         0.5f,  0.5f,  0.5f,
        -0.5f,  0.5f,  0.5f,
        -0.5f, -0.5f,  0.5f,

        -0.5f,  0.5f,  0.5f,
        -0.5f,  0.5f, -0.5f,
        -0.5f, -0.5f, -0.5f,
        -0.5f, -0.5f, -0.5f,
        -0.5f, -0.5f,  0.5f,
        -0.5f,  0.5f,  0.5f,

         0.5f,  0.5f,  0.5f,
         0.5f, -0.5f, -0.5f,
         0.5f,  0.5f, -0.5f,
         0.5f, -0.5f, -0.5f,
         0.5f,  0.5f,  0.5f,
         0.5f, -0.5f,  0.5f,

        -0.5f, -0.5f, -0.5f,
         0.5f, -0.5f, -0.5f,
         0.5f, -0.5f,  0.5f,
         0.5f, -0.5f,  0.5f,
        -0.5f, -0.5f,  0.5f,
        -0.5f, -0.5f, -0.5f,

        -0.5f,  0.5f, -0.5f,
         0.5f,  0.5f,  0.5f,
         0.5f,  0.5f, -0.5f,
         0.5f,  0.5f,  0.5f,
        -0.5f,  0.5f, -0.5f,
        -0.5f,  0.5f,  0.5f
    };

    // Setup cube VAO
    GLuint cubeVAO, cubeVBO;
    glGenVertexArrays(1, &cubeVAO);
    glGenBuffers(1, &cubeVBO);
    glBindVertexArray(cubeVAO);
    glBindBuffer(GL_ARRAY_BUFFER, cubeVBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(cubeVertices), &cubeVertices, GL_STATIC_DRAW);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0); 
    glBindVertexArray(0);

    #pragma endregion

    // create a uniform buffer object
    // first we get the relevant block indices
    GLuint uniformBlockIndexRed = glGetUniformBlockIndex(shaderRed.Program, "Matrices");
    GLuint uniformBlockIndexGreen = glGetUniformBlockIndex(shaderGreen.Program, "Matrices");
    GLuint uniformBlockIndexBlue = glGetUniformBlockIndex(shaderBlue.Program, "Matrices");
    GLuint uniformBlockIndexYellow = glGetUniformBlockIndex(shaderYellow.Program, "Matrices");

    // then we link each shader's uniform block to this uniform binding point
    glUniformBlockBinding(shaderRed.Program, uniformBlockIndexRed, 0);
    glUniformBlockBinding(shaderGreen.Program, uniformBlockIndexGreen, 0);
    glUniformBlockBinding(shaderBlue.Program, uniformBlockIndexBlue, 0);
    glUniformBlockBinding(shaderYellow.Program, uniformBlockIndexYellow, 0);

    // now actually create the buffer
    GLuint uboMatrices;
    glGenBuffers(1, &uboMatrices);
    glBindBuffer(GL_UNIFORM_BUFFER, uboMatrices);
    glBufferData(GL_UNIFORM_BUFFER, 2 * sizeof(glm::mat4), NULL, GL_STATIC_DRAW);
    glBindBuffer(GL_UNIFORM_BUFFER, 0);
    // define the range of the buffer that links to a uniform binding point...
    glBindBufferRange(GL_UNIFORM_BUFFER, 0, uboMatrices, 0, 2 * sizeof(glm::mat4));

    // store the projection matrix
    glm::mat4 projection = glm::perspective(45.0f, (float)screenWidth / (float)screenHeight, 0.1f, 100.0f);
    glBindBuffer(GL_UNIFORM_BUFFER, uboMatrices);
    glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(glm::mat4), glm::value_ptr(projection));
    glBindBuffer(GL_UNIFORM_BUFFER, 0);

    //glPolygonMode(GL_FRONT_AND_BACK, GL_POINT);
    // game loop
    while (!glfwWindowShouldClose(window)) {
        // Set frame time
        GLfloat currentFrame = glfwGetTime();
        deltaTime = currentFrame - lastFrame;
        lastFrame = currentFrame;

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

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

        //////////////////////////////////////////////////////////////////////////
        // set the view and projection matrix in the uniform block
        glm::mat4 view = camera.GetViewMatrix();
        glBindBuffer(GL_UNIFORM_BUFFER, uboMatrices);
        glBufferSubData(GL_UNIFORM_BUFFER, sizeof(glm::mat4), sizeof(glm::mat4), glm::value_ptr(view));
        glBindBuffer(GL_UNIFORM_BUFFER, 0);

        // draw 4 cubes
        //RED
        glBindVertexArray(cubeVAO);
        shaderRed.Use();
        glm::mat4 model;
        model = glm::translate(model, glm::vec3(-0.75f, 0.75f, 0.0f));
        glUniformMatrix4fv(glGetUniformLocation(shaderRed.Program, "model"), 1, GL_FALSE, glm::value_ptr(model));
        glDrawArrays(GL_TRIANGLES, 0, 36);
        ////GREEN
        //shaderGreen.Use();
        //model = glm::mat4();
        //model = glm::translate(model, glm::vec3(0.75f, 0.75f, 0.0f));
        //glUniformMatrix4fv(glGetUniformLocation(shaderGreen.Program, "model"), 1, GL_FALSE, glm::value_ptr(model));
        //glDrawArrays(GL_TRIANGLES, 0, 36);
        ////BLUE
        //shaderBlue.Use();
        //model = glm::mat4();
        //model = glm::translate(model, glm::vec3(-0.75f, -0.75f, 0.0f));
        //glUniformMatrix4fv(glGetUniformLocation(shaderBlue.Program, "model"), 1, GL_FALSE, glm::value_ptr(model));
        //glDrawArrays(GL_TRIANGLES, 0, 36);
        ////
        //shaderYellow.Use();
        //model = glm::mat4();
        //model = glm::translate(model, glm::vec3(0.75f, -0.75f, 0.0f));
        //glUniformMatrix4fv(glGetUniformLocation(shaderYellow.Program, "model"), 1, GL_FALSE, glm::value_ptr(model));
        //glDrawArrays(GL_TRIANGLES, 0, 36);

        //
        glfwSwapBuffers(window);
    }

    glfwTerminate();
    return 0;
}
Beispiel #12
0
bool FShader::Load(const char * name, const char * vert_prog_lump, const char * frag_prog_lump, const char * proc_prog_lump, const char * defines)
{
	static char buffer[10000];
	FString error;

	int i_lump = Wads.CheckNumForFullName("shaders/glsl/shaderdefs.i");
	if (i_lump == -1) I_Error("Unable to load 'shaders/glsl/shaderdefs.i'");
	FMemLump i_data = Wads.ReadLump(i_lump);

	int vp_lump = Wads.CheckNumForFullName(vert_prog_lump);
	if (vp_lump == -1) I_Error("Unable to load '%s'", vert_prog_lump);
	FMemLump vp_data = Wads.ReadLump(vp_lump);

	int fp_lump = Wads.CheckNumForFullName(frag_prog_lump);
	if (fp_lump == -1) I_Error("Unable to load '%s'", frag_prog_lump);
	FMemLump fp_data = Wads.ReadLump(fp_lump);



//
// The following code uses GetChars on the strings to get rid of terminating 0 characters. Do not remove or the code may break!
//
	unsigned int lightbuffertype = GLRenderer->mLights->GetBufferType();
	unsigned int lightbuffersize = GLRenderer->mLights->GetBlockSize();

	FString vp_comb;

	if (lightbuffertype == GL_UNIFORM_BUFFER)
	{
		if (gl.glslversion < 1.4f || gl.version < 3.1f)
		{
			vp_comb.Format("#version 130\n#extension GL_ARB_uniform_buffer_object : require\n#define NUM_UBO_LIGHTS %d\n", lightbuffersize);
		}
		else
		{
			vp_comb.Format("#version 140\n#define NUM_UBO_LIGHTS %d\n", lightbuffersize);
		}
	}
	else
	{
		vp_comb = "#version 400 core\n#extension GL_ARB_shader_storage_buffer_object : require\n#define SHADER_STORAGE_LIGHTS\n";
	}

	vp_comb << defines << i_data.GetString().GetChars();
	FString fp_comb = vp_comb;

	vp_comb << vp_data.GetString().GetChars() << "\n";
	fp_comb << fp_data.GetString().GetChars() << "\n";

	if (proc_prog_lump != NULL)
	{
		if (*proc_prog_lump != '#')
		{
			int pp_lump = Wads.CheckNumForFullName(proc_prog_lump);
			if (pp_lump == -1) I_Error("Unable to load '%s'", proc_prog_lump);
			FMemLump pp_data = Wads.ReadLump(pp_lump);

			if (pp_data.GetString().IndexOf("ProcessTexel") < 0)
			{
				// this looks like an old custom hardware shader.
				// We need to replace the ProcessTexel call to make it work.

				fp_comb.Substitute("vec4 frag = ProcessTexel();", "vec4 frag = Process(vec4(1.0));");
			}
			fp_comb << pp_data.GetString().GetChars();
			fp_comb.Substitute("gl_TexCoord[0]", "vTexCoord");	// fix old custom shaders.

			if (pp_data.GetString().IndexOf("ProcessLight") < 0)
			{
				int pl_lump = Wads.CheckNumForFullName("shaders/glsl/func_defaultlight.fp");
				if (pl_lump == -1) I_Error("Unable to load '%s'", "shaders/glsl/func_defaultlight.fp");
				FMemLump pl_data = Wads.ReadLump(pl_lump);
				fp_comb << "\n" << pl_data.GetString().GetChars();
			}
		}
		else
		{
			// Proc_prog_lump is not a lump name but the source itself (from generated shaders)
			fp_comb << proc_prog_lump + 1;
		}
	}

	hVertProg = glCreateShader(GL_VERTEX_SHADER);
	hFragProg = glCreateShader(GL_FRAGMENT_SHADER);	


	int vp_size = (int)vp_comb.Len();
	int fp_size = (int)fp_comb.Len();

	const char *vp_ptr = vp_comb.GetChars();
	const char *fp_ptr = fp_comb.GetChars();

	glShaderSource(hVertProg, 1, &vp_ptr, &vp_size);
	glShaderSource(hFragProg, 1, &fp_ptr, &fp_size);

	glCompileShader(hVertProg);
	glCompileShader(hFragProg);

	hShader = glCreateProgram();

	glAttachShader(hShader, hVertProg);
	glAttachShader(hShader, hFragProg);

	glBindAttribLocation(hShader, VATTR_VERTEX, "aPosition");
	glBindAttribLocation(hShader, VATTR_TEXCOORD, "aTexCoord");
	glBindAttribLocation(hShader, VATTR_COLOR, "aColor");
	glBindAttribLocation(hShader, VATTR_VERTEX2, "aVertex2");

	glLinkProgram(hShader);

	glGetShaderInfoLog(hVertProg, 10000, NULL, buffer);
	if (*buffer) 
	{
		error << "Vertex shader:\n" << buffer << "\n";
	}
	glGetShaderInfoLog(hFragProg, 10000, NULL, buffer);
	if (*buffer) 
	{
		error << "Fragment shader:\n" << buffer << "\n";
	}

	glGetProgramInfoLog(hShader, 10000, NULL, buffer);
	if (*buffer) 
	{
		error << "Linking:\n" << buffer << "\n";
	}
	int linked;
	glGetProgramiv(hShader, GL_LINK_STATUS, &linked);
	if (linked == 0)
	{
		// only print message if there's an error.
		I_Error("Init Shader '%s':\n%s\n", name, error.GetChars());
	}


	muDesaturation.Init(hShader, "uDesaturationFactor");
	muFogEnabled.Init(hShader, "uFogEnabled");
	muTextureMode.Init(hShader, "uTextureMode");
	muCameraPos.Init(hShader, "uCameraPos");
	muLightParms.Init(hShader, "uLightAttr");
	muClipSplit.Init(hShader, "uClipSplit");
	muColormapStart.Init(hShader, "uFixedColormapStart");
	muColormapRange.Init(hShader, "uFixedColormapRange");
	muLightIndex.Init(hShader, "uLightIndex");
	muFogColor.Init(hShader, "uFogColor");
	muDynLightColor.Init(hShader, "uDynLightColor");
	muObjectColor.Init(hShader, "uObjectColor");
	muGlowBottomColor.Init(hShader, "uGlowBottomColor");
	muGlowTopColor.Init(hShader, "uGlowTopColor");
	muGlowBottomPlane.Init(hShader, "uGlowBottomPlane");
	muGlowTopPlane.Init(hShader, "uGlowTopPlane");
	muFixedColormap.Init(hShader, "uFixedColormap");
	muInterpolationFactor.Init(hShader, "uInterpolationFactor");
	muClipHeightTop.Init(hShader, "uClipHeightTop");
	muClipHeightBottom.Init(hShader, "uClipHeightBottom");
	muAlphaThreshold.Init(hShader, "uAlphaThreshold");
	muTimer.Init(hShader, "timer");

	lights_index = glGetUniformLocation(hShader, "lights");
	fakevb_index = glGetUniformLocation(hShader, "fakeVB");
	projectionmatrix_index = glGetUniformLocation(hShader, "ProjectionMatrix");
	viewmatrix_index = glGetUniformLocation(hShader, "ViewMatrix");
	modelmatrix_index = glGetUniformLocation(hShader, "ModelMatrix");
	texturematrix_index = glGetUniformLocation(hShader, "TextureMatrix");

	int tempindex = glGetUniformBlockIndex(hShader, "LightBufferUBO");
	if (tempindex != -1) glUniformBlockBinding(hShader, tempindex, LIGHTBUF_BINDINGPOINT);

	glUseProgram(hShader);

	// set up other texture units (if needed by the shader)
	for (int i = 2; i<16; i++)
	{
		char stringbuf[20];
		mysnprintf(stringbuf, 20, "texture%d", i);
		tempindex = glGetUniformLocation(hShader, stringbuf);
		if (tempindex > 0) glUniform1i(tempindex, i - 1);
	}

	glUseProgram(0);
	return !!linked;
}
Beispiel #13
0
 void AssignUniforms_impl()
 {
     GLuint uniform_ViewProjectionMatrixesUBO = glGetUniformBlockIndex(Program, "MatrixesData");
     if (uniform_ViewProjectionMatrixesUBO != GL_INVALID_INDEX)
         glUniformBlockBinding(Program, uniform_ViewProjectionMatrixesUBO, 0);
 }
void CollisionGeometry::bind(const GLuint shaderProgram,const GLuint bindingPoint, const std::string &blockName) const
{
  GLuint uniformBlockIndex = glGetUniformBlockIndex(shaderProgram, blockName.c_str());
  glUniformBlockBinding(shaderProgram, uniformBlockIndex, bindingPoint);
  glBindBufferRange(GL_UNIFORM_BUFFER, bindingPoint, mUniformBuffer, 0, sizeof(float)*56);
}
Beispiel #15
0
void LightSystem::renderLight() {
    // creating temporary data that will be send to light buffer
    glGenBuffers(1, &LightBuffer);

    glBindBuffer(GL_UNIFORM_BUFFER, LightBuffer);
    int lc = lightList.size();

    const GLchar *uniformNames[1] = { "Lights.cont" };
    GLuint uniformIndices;

    glGetUniformIndices(*shader, 1, uniformNames, &uniformIndices);

    GLint uniformOffsets[1];
    glGetActiveUniformsiv(*shader, 1, &uniformIndices, GL_UNIFORM_OFFSET,
            uniformOffsets);

    GLuint uniformIndex = glGetUniformBlockIndex(*shader, "Lights");

    GLsizei uniformBlockSize(0);
    glGetActiveUniformBlockiv(*shader, uniformIndex, GL_UNIFORM_BLOCK_DATA_SIZE,
            &uniformBlockSize);

    GLint maxSize;
    glGetIntegerv(GL_MAX_UNIFORM_BLOCK_SIZE, &maxSize);
    GLint bufferAlignment;
    glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, &bufferAlignment);

    //std::cout << "Uniform Block size: " << uniformBlockSize << std::endl;
    //std::cout << "Uniform Block max size: " << maxSize << std::endl;
    //std::cout << "Uniform Buffer alignment: " << bufferAlignment << std::endl;

    GLuint indices[lc * 2];

    glGetUniformIndices(*shader, lc * 2, names, indices);

    lightUniformOffsets.clear();
    lightUniformOffsets.resize(lc * 2);

    glGetActiveUniformsiv(*shader, lightUniformOffsets.size(), indices,
            GL_UNIFORM_OFFSET, &lightUniformOffsets[0]);
    GLint *offsets = &lightUniformOffsets[0];

    unsigned int bSize(uniformBlockSize);
    std::vector<unsigned char> buffer(bSize);

    int offset;

    for (unsigned int n = 0; n < lightList.size(); ++n) {
        offset = offsets[0 + n * 2];

        *(reinterpret_cast<GLfloat*>(&buffer[0] + offset)) = lightList[n].position.x;
        offset += sizeof(GLfloat);
        *(reinterpret_cast<GLfloat*>(&buffer[0] + offset)) = lightList[n].position.y;
        offset += sizeof(GLfloat);
        *(reinterpret_cast<GLfloat*>(&buffer[0] + offset)) = lightList[n].position.z;
        offset += sizeof(GLfloat);

        offset = offsets[1 + n * 2];
        *(reinterpret_cast<GLfloat*>(&buffer[0] + offset)) =
                lightList[n].color.x;
        offset += sizeof(GLfloat);
        *(reinterpret_cast<GLfloat*>(&buffer[0] + offset)) =
                lightList[n].color.y;
        offset += sizeof(GLfloat);
        *(reinterpret_cast<GLfloat*>(&buffer[0] + offset)) =
                lightList[n].color.z;
        offset += sizeof(GLfloat);
    }

    glUniform1i(LightCount, lc);

    glBufferData(GL_UNIFORM_BUFFER, bSize, &buffer[0], GL_DYNAMIC_DRAW);
    glBindBufferBase(GL_UNIFORM_BUFFER, 0, LightBuffer);
    glUniformBlockBinding(*shader, uniformIndex, 0);
    glBindBuffer(GL_UNIFORM_BUFFER, 0);
}
Beispiel #16
0
void Shader::BindUniformBlock(const std::string& name, const uint32_t mUniformBufferBindingIndex)
{
	auto location = GetUniformBlockLocation(mShaderProgram, name);
	glUniformBlockBinding(mShaderProgram, location, mUniformBufferBindingIndex);
}
Beispiel #17
0
bool FShader::Load(const char * name, const char * vert_prog_lump, const char * frag_prog_lump, const char * proc_prog_lump, const char * defines)
{
	static char buffer[10000];
	FString error;

	int i_lump = Wads.CheckNumForFullName("shaders/glsl/shaderdefs.i", 0);
	if (i_lump == -1) I_Error("Unable to load 'shaders/glsl/shaderdefs.i'");
	FMemLump i_data = Wads.ReadLump(i_lump);

	int vp_lump = Wads.CheckNumForFullName(vert_prog_lump, 0);
	if (vp_lump == -1) I_Error("Unable to load '%s'", vert_prog_lump);
	FMemLump vp_data = Wads.ReadLump(vp_lump);

	int fp_lump = Wads.CheckNumForFullName(frag_prog_lump, 0);
	if (fp_lump == -1) I_Error("Unable to load '%s'", frag_prog_lump);
	FMemLump fp_data = Wads.ReadLump(fp_lump);



//
// The following code uses GetChars on the strings to get rid of terminating 0 characters. Do not remove or the code may break!
//
	FString vp_comb;

	assert(GLRenderer->mLights != NULL);
	// On the shader side there is no difference between LM_DEFERRED and LM_DIRECT, it only decides how the buffer is initialized.
	unsigned int lightbuffertype = GLRenderer->mLights->GetBufferType();
	unsigned int lightbuffersize = GLRenderer->mLights->GetBlockSize();
	if (lightbuffertype == GL_UNIFORM_BUFFER)
	{
		// This differentiation is for some Intel drivers which fail on #extension, so use of #version 140 is necessary
		if (gl.glslversion < 1.4f)
		{
			vp_comb.Format("#version 130\n#extension GL_ARB_uniform_buffer_object : require\n#define NUM_UBO_LIGHTS %d\n", lightbuffersize);
		}
		else
		{
			vp_comb.Format("#version 140\n#define NUM_UBO_LIGHTS %d\n", lightbuffersize);
		}
	}
	else
	{
		vp_comb = "#version 400 core\n#extension GL_ARB_shader_storage_buffer_object : require\n#define SHADER_STORAGE_LIGHTS\n";
	}

	if (gl.buffermethod == BM_DEFERRED)
	{
		vp_comb << "#define USE_QUAD_DRAWER\n";
	}

	vp_comb << defines << i_data.GetString().GetChars();
	FString fp_comb = vp_comb;

	vp_comb << vp_data.GetString().GetChars() << "\n";
	fp_comb << fp_data.GetString().GetChars() << "\n";

	if (proc_prog_lump != NULL)
	{
		if (*proc_prog_lump != '#')
		{
			int pp_lump = Wads.CheckNumForFullName(proc_prog_lump);
			if (pp_lump == -1) I_Error("Unable to load '%s'", proc_prog_lump);
			FMemLump pp_data = Wads.ReadLump(pp_lump);

			if (pp_data.GetString().IndexOf("ProcessTexel") < 0)
			{
				// this looks like an old custom hardware shader.
				// We need to replace the ProcessTexel call to make it work.

				fp_comb.Substitute("vec4 frag = ProcessTexel();", "vec4 frag = Process(vec4(1.0));");
			}
			fp_comb << pp_data.GetString().GetChars();
			fp_comb.Substitute("gl_TexCoord[0]", "vTexCoord");	// fix old custom shaders.

			if (pp_data.GetString().IndexOf("ProcessLight") < 0)
			{
				int pl_lump = Wads.CheckNumForFullName("shaders/glsl/func_defaultlight.fp");
				if (pl_lump == -1) I_Error("Unable to load '%s'", "shaders/glsl/func_defaultlight.fp");
				FMemLump pl_data = Wads.ReadLump(pl_lump);
				fp_comb << "\n" << pl_data.GetString().GetChars();
			}
		}
		else
		{
			// Proc_prog_lump is not a lump name but the source itself (from generated shaders)
			fp_comb << proc_prog_lump + 1;
		}
	}

	if (gl.flags & RFL_NO_CLIP_PLANES)
	{
		// On ATI's GL3 drivers we have to disable gl_ClipDistance because it's hopelessly broken.
		// This will cause some glitches and regressions but is the only way to avoid total display garbage.
		vp_comb.Substitute("gl_ClipDistance", "//");
	}

	hVertProg = glCreateShader(GL_VERTEX_SHADER);
	hFragProg = glCreateShader(GL_FRAGMENT_SHADER);	

	FGLDebug::LabelObject(GL_SHADER, hVertProg, vert_prog_lump);
	FGLDebug::LabelObject(GL_SHADER, hFragProg, frag_prog_lump);

	int vp_size = (int)vp_comb.Len();
	int fp_size = (int)fp_comb.Len();

	const char *vp_ptr = vp_comb.GetChars();
	const char *fp_ptr = fp_comb.GetChars();

	glShaderSource(hVertProg, 1, &vp_ptr, &vp_size);
	glShaderSource(hFragProg, 1, &fp_ptr, &fp_size);

	glCompileShader(hVertProg);
	glCompileShader(hFragProg);

	hShader = glCreateProgram();
	FGLDebug::LabelObject(GL_PROGRAM, hShader, name);

	glAttachShader(hShader, hVertProg);
	glAttachShader(hShader, hFragProg);

	glBindAttribLocation(hShader, VATTR_VERTEX, "aPosition");
	glBindAttribLocation(hShader, VATTR_TEXCOORD, "aTexCoord");
	glBindAttribLocation(hShader, VATTR_COLOR, "aColor");
	glBindAttribLocation(hShader, VATTR_VERTEX2, "aVertex2");
	glBindAttribLocation(hShader, VATTR_NORMAL, "aNormal");

	glBindFragDataLocation(hShader, 0, "FragColor");
	glBindFragDataLocation(hShader, 1, "FragFog");
	glBindFragDataLocation(hShader, 2, "FragNormal");

	glLinkProgram(hShader);

	glGetShaderInfoLog(hVertProg, 10000, NULL, buffer);
	if (*buffer) 
	{
		error << "Vertex shader:\n" << buffer << "\n";
	}
	glGetShaderInfoLog(hFragProg, 10000, NULL, buffer);
	if (*buffer) 
	{
		error << "Fragment shader:\n" << buffer << "\n";
	}

	glGetProgramInfoLog(hShader, 10000, NULL, buffer);
	if (*buffer) 
	{
		error << "Linking:\n" << buffer << "\n";
	}
	int linked;
	glGetProgramiv(hShader, GL_LINK_STATUS, &linked);
	if (linked == 0)
	{
		// only print message if there's an error.
		I_Error("Init Shader '%s':\n%s\n", name, error.GetChars());
	}


	muDesaturation.Init(hShader, "uDesaturationFactor");
	muFogEnabled.Init(hShader, "uFogEnabled");
	muPalLightLevels.Init(hShader, "uPalLightLevels");
	muTextureMode.Init(hShader, "uTextureMode");
	muCameraPos.Init(hShader, "uCameraPos");
	muLightParms.Init(hShader, "uLightAttr");
	muClipSplit.Init(hShader, "uClipSplit");
	muColormapStart.Init(hShader, "uFixedColormapStart");
	muColormapRange.Init(hShader, "uFixedColormapRange");
	muLightIndex.Init(hShader, "uLightIndex");
	muFogColor.Init(hShader, "uFogColor");
	muDynLightColor.Init(hShader, "uDynLightColor");
	muObjectColor.Init(hShader, "uObjectColor");
	muObjectColor2.Init(hShader, "uObjectColor2");
	muGlowBottomColor.Init(hShader, "uGlowBottomColor");
	muGlowTopColor.Init(hShader, "uGlowTopColor");
	muGlowBottomPlane.Init(hShader, "uGlowBottomPlane");
	muGlowTopPlane.Init(hShader, "uGlowTopPlane");
	muSplitBottomPlane.Init(hShader, "uSplitBottomPlane");
	muSplitTopPlane.Init(hShader, "uSplitTopPlane");
	muClipLine.Init(hShader, "uClipLine");
	muFixedColormap.Init(hShader, "uFixedColormap");
	muInterpolationFactor.Init(hShader, "uInterpolationFactor");
	muClipHeight.Init(hShader, "uClipHeight");
	muClipHeightDirection.Init(hShader, "uClipHeightDirection");
	muAlphaThreshold.Init(hShader, "uAlphaThreshold");
	muTimer.Init(hShader, "timer");

	lights_index = glGetUniformLocation(hShader, "lights");
	fakevb_index = glGetUniformLocation(hShader, "fakeVB");
	projectionmatrix_index = glGetUniformLocation(hShader, "ProjectionMatrix");
	viewmatrix_index = glGetUniformLocation(hShader, "ViewMatrix");
	modelmatrix_index = glGetUniformLocation(hShader, "ModelMatrix");
	texturematrix_index = glGetUniformLocation(hShader, "TextureMatrix");
	vertexmatrix_index = glGetUniformLocation(hShader, "uQuadVertices");
	texcoordmatrix_index = glGetUniformLocation(hShader, "uQuadTexCoords");
	normalviewmatrix_index = glGetUniformLocation(hShader, "NormalViewMatrix");
	normalmodelmatrix_index = glGetUniformLocation(hShader, "NormalModelMatrix");
	quadmode_index = glGetUniformLocation(hShader, "uQuadMode");

	if (!gl.legacyMode && !(gl.flags & RFL_SHADER_STORAGE_BUFFER))
	{
		int tempindex = glGetUniformBlockIndex(hShader, "LightBufferUBO");
		if (tempindex != -1) glUniformBlockBinding(hShader, tempindex, LIGHTBUF_BINDINGPOINT);
	}

	glUseProgram(hShader);
	if (quadmode_index > 0) glUniform1i(quadmode_index, 0);

	// set up other texture units (if needed by the shader)
	for (int i = 2; i<16; i++)
	{
		char stringbuf[20];
		mysnprintf(stringbuf, 20, "texture%d", i);
		int tempindex = glGetUniformLocation(hShader, stringbuf);
		if (tempindex > 0) glUniform1i(tempindex, i - 1);
	}

	glUseProgram(0);
	return !!linked;
}
Beispiel #18
0
bool ShaderProgram::Link()
{
    Release();

    if (!vertexShader_ || !pixelShader_ || !vertexShader_->GetGPUObject() || !pixelShader_->GetGPUObject())
        return false;

    object_ = glCreateProgram();
    if (!object_)
    {
        linkerOutput_ = "Could not create shader program";
        return false;
    }

    glAttachShader(object_, vertexShader_->GetGPUObject());
    glAttachShader(object_, pixelShader_->GetGPUObject());
    glLinkProgram(object_);

    int linked, length;
    glGetProgramiv(object_, GL_LINK_STATUS, &linked);
    if (!linked)
    {
        glGetProgramiv(object_, GL_INFO_LOG_LENGTH, &length);
        linkerOutput_.Resize((unsigned)length);
        int outLength;
        glGetProgramInfoLog(object_, length, &outLength, &linkerOutput_[0]);
        glDeleteProgram(object_);
        object_ = 0;
    }
    else
        linkerOutput_.Clear();

    if (!object_)
        return false;

    const int MAX_NAME_LENGTH = 256;
    char nameBuffer[MAX_NAME_LENGTH];
    int attributeCount, uniformCount, elementCount, nameLength;
    GLenum type;

    glUseProgram(object_);

    // Check for vertex attributes
    glGetProgramiv(object_, GL_ACTIVE_ATTRIBUTES, &attributeCount);
    for (int i = 0; i < attributeCount; ++i)
    {
        glGetActiveAttrib(object_, i, (GLsizei)MAX_NAME_LENGTH, &nameLength, &elementCount, &type, nameBuffer);

        String name = String(nameBuffer, nameLength);
        VertexElementSemantic semantic = MAX_VERTEX_ELEMENT_SEMANTICS;
        unsigned char semanticIndex = 0;

        // Go in reverse order so that "binormal" is detected before "normal"
        for (unsigned j = MAX_VERTEX_ELEMENT_SEMANTICS - 1; j < MAX_VERTEX_ELEMENT_SEMANTICS; --j)
        {
            if (name.Contains(elementSemanticNames[j], false))
            {
                semantic = (VertexElementSemantic)j;
                unsigned index = NumberPostfix(name);
                if (index != M_MAX_UNSIGNED)
                    semanticIndex = (unsigned char)index;
                break;
            }
        }

        if (semantic == MAX_VERTEX_ELEMENT_SEMANTICS)
        {
            URHO3D_LOGWARNING("Found vertex attribute " + name + " with no known semantic in shader program " + 
                vertexShader_->GetFullName() + " " + pixelShader_->GetFullName());
            continue;
        }

        int location = glGetAttribLocation(object_, name.CString());
        vertexAttributes_[MakePair((unsigned char)semantic, semanticIndex)] = location;
        usedVertexAttributes_ |= (1 << location);
    }

    // Check for constant buffers
#ifndef GL_ES_VERSION_2_0
    HashMap<unsigned, unsigned> blockToBinding;

    if (Graphics::GetGL3Support())
    {
        int numUniformBlocks = 0;

        glGetProgramiv(object_, GL_ACTIVE_UNIFORM_BLOCKS, &numUniformBlocks);
        for (int i = 0; i < numUniformBlocks; ++i)
        {
            glGetActiveUniformBlockName(object_, (GLuint)i, MAX_NAME_LENGTH, &nameLength, nameBuffer);

            String name(nameBuffer, (unsigned)nameLength);

            unsigned blockIndex = glGetUniformBlockIndex(object_, name.CString());
            unsigned group = M_MAX_UNSIGNED;

            // Try to recognize the use of the buffer from its name
            for (unsigned j = 0; j < MAX_SHADER_PARAMETER_GROUPS; ++j)
            {
                if (name.Contains(shaderParameterGroups[j], false))
                {
                    group = j;
                    break;
                }
            }

            // If name is not recognized, search for a digit in the name and use that as the group index
            if (group == M_MAX_UNSIGNED)
                group = NumberPostfix(name);

            if (group >= MAX_SHADER_PARAMETER_GROUPS)
            {
                URHO3D_LOGWARNING("Skipping unrecognized uniform block " + name + " in shader program " + vertexShader_->GetFullName() +
                           " " + pixelShader_->GetFullName());
                continue;
            }

            // Find total constant buffer data size
            int dataSize;
            glGetActiveUniformBlockiv(object_, blockIndex, GL_UNIFORM_BLOCK_DATA_SIZE, &dataSize);
            if (!dataSize)
                continue;

            unsigned bindingIndex = group;
            // Vertex shader constant buffer bindings occupy slots starting from zero to maximum supported, pixel shader bindings
            // from that point onward
            if (name.Contains("PS", false))
                bindingIndex += MAX_SHADER_PARAMETER_GROUPS;

            glUniformBlockBinding(object_, blockIndex, bindingIndex);
            blockToBinding[blockIndex] = bindingIndex;

            constantBuffers_[bindingIndex] = graphics_->GetOrCreateConstantBuffer(bindingIndex, (unsigned)dataSize);
        }
    }
#endif

    // Check for shader parameters and texture units
    glGetProgramiv(object_, GL_ACTIVE_UNIFORMS, &uniformCount);
    for (int i = 0; i < uniformCount; ++i)
    {
        glGetActiveUniform(object_, (GLuint)i, MAX_NAME_LENGTH, 0, &elementCount, &type, nameBuffer);
        int location = glGetUniformLocation(object_, nameBuffer);

        // Check for array index included in the name and strip it
        String name(nameBuffer);
        unsigned index = name.Find('[');
        if (index != String::NPOS)
        {
            // If not the first index, skip
            if (name.Find("[0]", index) == String::NPOS)
                continue;

            name = name.Substring(0, index);
        }

        if (name[0] == 'c')
        {
            // Store constant uniform
            String paramName = name.Substring(1);
            ShaderParameter newParam;
            newParam.type_ = type;
            newParam.location_ = location;

#ifndef GL_ES_VERSION_2_0
            // If running OpenGL 3, the uniform may be inside a constant buffer
            if (newParam.location_ < 0 && Graphics::GetGL3Support())
            {
                int blockIndex, blockOffset;
                glGetActiveUniformsiv(object_, 1, (const GLuint*)&i, GL_UNIFORM_BLOCK_INDEX, &blockIndex);
                glGetActiveUniformsiv(object_, 1, (const GLuint*)&i, GL_UNIFORM_OFFSET, &blockOffset);
                if (blockIndex >= 0)
                {
                    newParam.location_ = blockOffset;
                    newParam.bufferPtr_ = constantBuffers_[blockToBinding[blockIndex]];
                }
            }
#endif

            if (newParam.location_ >= 0)
                shaderParameters_[StringHash(paramName)] = newParam;
        }
        else if (location >= 0 && name[0] == 's')
        {
            // Set the samplers here so that they do not have to be set later
            unsigned unit = graphics_->GetTextureUnit(name.Substring(1));
            if (unit >= MAX_TEXTURE_UNITS)
                unit = NumberPostfix(name);

            if (unit < MAX_TEXTURE_UNITS)
            {
                useTextureUnit_[unit] = true;
                glUniform1iv(location, 1, reinterpret_cast<int*>(&unit));
            }
        }
    }

    // Rehash the parameter & vertex attributes maps to ensure minimal load factor
    vertexAttributes_.Rehash(NextPowerOfTwo(vertexAttributes_.Size()));
    shaderParameters_.Rehash(NextPowerOfTwo(shaderParameters_.Size()));

    return true;
}
Beispiel #19
0
void Test10::Init(){
	cout<<endl<<"INIT TEST 10 FRAMEBUFFERS"<<endl;
	pla_activat = false;
	/*************** 0 -- Retrec l'apuntador al objecte VIDEO MANAGER per no fer una indireccio més cada cop */
	VideoManager *m_video_manager_pointer = VideoManager::GetInstance();

	/************ 1 -- CARREGO OBJECTES ********************/

	m_mesh = new Mesh_OBJ2();
	m_mesh->CarregaFitxer("cub256text.obj");
	m_mesh_pla = new Mesh_OBJ2();
	m_mesh_pla->CarregaFitxer("pla1280.obj");

	m_mesh_donut = new Mesh_OBJ2();
	m_mesh_donut->CarregaFitxer("donut.obj");

	m_mesh_esfera = new Mesh_OBJ2();
	m_mesh_esfera->CarregaFitxer("esfera32.obj");



	/************  2 -- CREO UN PROGRAMA AMB ELS SHADERS ***************/


	m_GL_program = new CGLProgram();
	m_GL_program->AttachShader("recursos/shaders/Test10.vert",GL_VERTEX_SHADER);
	m_GL_program->AttachShader("recursos/shaders/Test10.frag",GL_FRAGMENT_SHADER);
	// FAIG QUE EL ATRIBUT 0 (QUE SON LES CORDENADES DELS VERTEX) ENTRIN a "in_Position" al vertex shader
	m_GL_program->Bind_Attribute_Location(0,"in_Position");
	m_GL_program->Bind_Attribute_Location(1,"in_Normals");
	m_GL_program->Link();
	//CARREGO UNIFORMS
	GLuint l_block_index = glGetUniformBlockIndex(m_GL_program->m_ID,"MatriusGlobals");
	glUniformBlockBinding(m_GL_program->m_ID,l_block_index,0);
	glBindBufferRange(GL_UNIFORM_BUFFER,0,m_video_manager_pointer->Get_UBO_Matrius_globals_location(),0 * sizeof(glm::mat4),2*sizeof(glm::mat4));


	m_GL_program_normal = new CGLProgram();
	m_GL_program_normal->AttachShader("recursos/shaders/Test10normal.vert",GL_VERTEX_SHADER);
	m_GL_program_normal->AttachShader("recursos/shaders/Test10normal.frag",GL_FRAGMENT_SHADER);
	// FAIG QUE EL ATRIBUT 0 (QUE SON LES CORDENADES DELS VERTEX) ENTRIN a "in_Position" al vertex shader
	m_GL_program_normal->Bind_Attribute_Location(0,"in_Position");
	m_GL_program_normal->Bind_Attribute_Location(1,"in_Normals");
	m_GL_program_normal->Link();
	//CARREGO UNIFORMS
	l_block_index = glGetUniformBlockIndex(m_GL_program_normal->m_ID,"MatriusGlobals");
	glUniformBlockBinding(m_GL_program_normal->m_ID,l_block_index,0);
	glBindBufferRange(GL_UNIFORM_BUFFER,0,m_video_manager_pointer->Get_UBO_Matrius_globals_location(),0 * sizeof(glm::mat4),2*sizeof(glm::mat4));



	//CARREGO UNA LLUM
	m_llum = new CGLLlum(vec3(0.0,32.0,0.0),vec3(0.8,0.7,0.5),0.2);
	m_posicio_camera = new CGLLlum(vec3(0.0,32.0,75.0),vec3(0.0,0.0,0.5),0.0);

	/************  2 -- CREO UN PROGRAMA AMB ELS SHADERS ***************/
/*
	m_GL_program = new CGLProgram();
	m_GL_program->AttachShader("recursos/shaders/Test10.vert",GL_VERTEX_SHADER);
	m_GL_program->AttachShader("recursos/shaders/Test10.frag",GL_FRAGMENT_SHADER);
	// FAIG QUE EL ATRIBUT 0 (QUE SON LES CORDENADES DELS VERTEX) ENTRIN a "in_Position" al vertex shader
	m_GL_program->Bind_Attribute_Location(0,"in_Position");
	m_GL_program->Bind_Attribute_Location(1,"in_Normals");
	m_GL_program->Bind_Attribute_Location(2,"in_Texture_coords");
	m_GL_program->Link();
	GLuint l_block_index = glGetUniformBlockIndex(m_GL_program->m_ID,"MatriusGlobals");
	glUniformBlockBinding(m_GL_program->m_ID,l_block_index,0);
	glBindBufferRange(GL_UNIFORM_BUFFER,0,m_video_manager_pointer->Get_UBO_Matrius_globals_location(),0 * sizeof(glm::mat4),2*sizeof(glm::mat4));
	m_GL_program->UnUse();

*/

	/*SEGON PROGRAMA PER EL PLA*/
	m_GL_program_RText = new CGLProgram();
	m_GL_program_RText->AttachShader("recursos/shaders/Test7.vert",GL_VERTEX_SHADER);
	m_GL_program_RText->AttachShader("recursos/shaders/Test7.frag",GL_FRAGMENT_SHADER);
	//m_GL_program_RText->AttachShader("recursos/shaders/VeureZBuffer.vert",GL_VERTEX_SHADER);
	//m_GL_program_RText->AttachShader("recursos/shaders/VeureZBuffer.frag",GL_FRAGMENT_SHADER);
	// FAIG QUE EL ATRIBUT 0 (QUE SON LES CORDENADES DELS VERTEX) ENTRIN a "in_Position" al vertex shader
	m_GL_program_RText->Bind_Attribute_Location(0,"in_Position");
	m_GL_program_RText->Bind_Attribute_Location(1,"in_Normals");
	m_GL_program_RText->Bind_Attribute_Location(2,"in_Texture_coords");
	m_GL_program_RText->Link();
	l_block_index = glGetUniformBlockIndex(m_GL_program_RText->m_ID,"MatriusGlobals");
	glUniformBlockBinding(m_GL_program_RText->m_ID,l_block_index,0);
	glBindBufferRange(GL_UNIFORM_BUFFER,0,m_video_manager_pointer->Get_UBO_Matrius_globals_location(),0 * sizeof(glm::mat4),2*sizeof(glm::mat4));
	m_GL_program_RText->UnUse();






	//FRAMEBUFFERS
	//CREATE FB TEXTURE

	glGenTextures(1, &m_FBOcolor_textura);
	glBindTexture(GL_TEXTURE_2D, m_FBOcolor_textura);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 1280, 720, 0,GL_RGBA,GL_UNSIGNED_BYTE , 0);
	glBindTexture(GL_TEXTURE_2D, 0);

	glGenTextures(1, &m_FBOdepth_textura);
	glBindTexture(GL_TEXTURE_2D, m_FBOdepth_textura);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, 1280, 720, 0,GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, 0);
	glBindTexture(GL_TEXTURE_2D, 0);



	glGenFramebuffers(1, &m_FBO);
	glBindFramebuffer(GL_FRAMEBUFFER, m_FBO);
	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,GL_TEXTURE_2D, m_FBOdepth_textura,0);
	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,GL_TEXTURE_2D, m_FBOcolor_textura,0);

	//glDrawBuffer(GL_COLOR_ATTACHMENT0);
	//glReadBuffer(GL_NONE);
	// check FBO status
	GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
	if(status != GL_FRAMEBUFFER_COMPLETE)
	{	cout<<"FBO NO OK!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"<<status<<endl;

	}

	// switch back to window-system-provided framebuffer
	glBindFramebuffer(GL_FRAMEBUFFER, 0);



}
void rglUniformBlockBinding(unsigned int programBuffer, unsigned int uniformBlockIndex, unsigned int uBOBindingIndex)
{
	GLCALL(glUniformBlockBinding(programBuffer, uniformBlockIndex, uBOBindingIndex));
}