Exemplo n.º 1
0
Arquivo: blit.c Projeto: Zoxc/piglit
bool
testFramebufferBlitLayered(int x, int y, bool srcLayered, bool dstLayered)
{
	bool pass = true;
	GLuint srcFBO, dstFBO;
	GLuint srcTex, dstTex;
	GLenum fbStatus;

	/* Set up source fbo */
	glGenFramebuffers(1, &srcFBO);
	glBindFramebuffer(GL_FRAMEBUFFER, srcFBO);

	piglit_check_gl_error(GL_NO_ERROR);
	if (srcLayered) {
		srcTex = create_bind_texture(GL_TEXTURE_3D, true);
		glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
				     srcTex, 0);
	} else {
		srcTex = create_bind_texture(GL_TEXTURE_2D, true);
		glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
				     GL_TEXTURE_2D, srcTex, 0);
	}

	/* Check source framebuffer status */
	fbStatus = glCheckFramebufferStatus(GL_FRAMEBUFFER);
	if (fbStatus != GL_FRAMEBUFFER_COMPLETE) {
		printf("testFramebufferBlitLayered srcFBO Status: %s\n",
		       piglit_get_gl_enum_name(fbStatus));
		return false;
	}

	/* Set up dstt fbo */
	glGenFramebuffers(1, &dstFBO);
	glBindFramebuffer(GL_FRAMEBUFFER, dstFBO);

	if (dstLayered) {
		dstTex = create_bind_texture(GL_TEXTURE_3D, false);
		glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
				     dstTex, 0);
	} else {
		dstTex = create_bind_texture(GL_TEXTURE_2D, false);
		glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
				       GL_TEXTURE_2D, dstTex, 0);
	}

	/* Check destination framebuffer status */
	fbStatus = glCheckFramebufferStatus(GL_FRAMEBUFFER);
	if (fbStatus != GL_FRAMEBUFFER_COMPLETE) {
		printf("testFramebufferBlitLayered dstFBO Status: %s\n",
		       piglit_get_gl_enum_name(fbStatus));
		return false;
	}

	/* Check for if any errors have occured */
	if (!piglit_check_gl_error(GL_NO_ERROR)) {
		printf("Error setting up framebuffers for test.\n");
		return false;
	}

	/* Blit from source to destination framebuffers */
	glBindFramebuffer(GL_READ_FRAMEBUFFER, srcFBO);
	glBindFramebuffer(GL_DRAW_FRAMEBUFFER, dstFBO);
	glBlitFramebuffer(0, 0, texWidth, texHeight,
			  0, 0, texWidth, texHeight,
			  GL_COLOR_BUFFER_BIT, GL_LINEAR);

	/* Display the results */
	display_texture(x, y, srcTex, srcLayered ? texDepth : 1);
	display_texture(x + texWidth, y, dstTex, dstLayered ? texDepth : 1);

	/* Check for pass condition */
	if (dstLayered) {
		pass = piglit_probe_rect_rgb(x + texWidth, y,
                                texWidth, texHeight, srcColors[0]) && pass;
		pass = piglit_probe_rect_rgb(x + texWidth, y + texHeight,
                                texWidth, texHeight, dstColors[1]) && pass;
	} else {
		pass = piglit_probe_rect_rgb(x + texWidth, y, texWidth,
                                texDepth * texHeight, srcColors[0]) && pass;
	}

	/* Clean up */
	glBindFramebuffer(GL_FRAMEBUFFER, piglit_winsys_fbo);
	glDeleteFramebuffers(1, &srcFBO);
	glDeleteFramebuffers(1, &dstFBO);
	glDeleteTextures(1, &srcTex);
	glDeleteTextures(1, &dstTex);

	/* Check for if any errors have occured */
	if (!piglit_check_gl_error(GL_NO_ERROR)) {
		printf("Error setting up framebuffers for test.\n");
		return false;
	}

	return pass;
}
Exemplo n.º 2
0
void SuzanneGL::RenderShadowMaps()
{
	GLuint FramebufferName = 0;
	glCreateFramebuffers(1, &FramebufferName);
	glBindFramebuffer(GL_FRAMEBUFFER, FramebufferName);

	glm::mat4 depthViewProjectionMatrices[NUMBER_OF_LIGHTS];
	for (int i = 0; i < NUMBER_OF_LIGHTS; ++i)
	{
		glCreateTextures(GL_TEXTURE_2D, 1, &shadowMaps[i]);
		glTextureImage2DEXT(shadowMaps[i], GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, SHADOW_RESOLUTION, SHADOW_RESOLUTION, 0, GL_DEPTH_COMPONENT, GL_FLOAT, 0);
		glTextureParameteri(shadowMaps[i], GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTextureParameteri(shadowMaps[i], GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		glTextureParameteri(shadowMaps[i], GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
		glTextureParameteri(shadowMaps[i], GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
		glTextureParameteri(shadowMaps[i], GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);
		glTextureParameteri(shadowMaps[i], GL_TEXTURE_COMPARE_MODE, GL_COMPARE_R_TO_TEXTURE);

		glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, shadowMaps[i], 0);

		glDrawBuffer(GL_NONE);

		if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
			return;

		glEnable(GL_DEPTH_TEST);
		glClear(GL_DEPTH_BUFFER_BIT);
		glViewport(0, 0, SHADOW_RESOLUTION, SHADOW_RESOLUTION);

		glm::vec3 lightDir = glm::normalize(glm::vec3(lighting.lights[i].position.x, lighting.lights[i].position.y, lighting.lights[i].position.z));
		glm::mat4 depthProjectionMatrix = glm::ortho<float>(-10, 10, -10, 10, -10, 20);
		glm::mat4 depthViewMatrix = glm::lookAt(lightDir, glm::vec3(0, 0, 0), glm::vec3(0, 1, 0));
		depthViewProjectionMatrices[i] = depthProjectionMatrix * depthViewMatrix;

		shadowModelMatrixIndex = glGetUniformLocation(shadowShaderProgram, "modelMatrix");
		shadowViewProjectionMatrixIndex = glGetUniformLocation(shadowShaderProgram, "viewProjectionMatrix");

		glProgramUniformMatrix4fv(shadowShaderProgram, shadowViewProjectionMatrixIndex, 1, GL_FALSE, glm::value_ptr(depthViewProjectionMatrices[i]));

		for (ModelGL model : models)
		{
			glProgramUniformMatrix4fv(shadowShaderProgram, shadowModelMatrixIndex, 1, GL_FALSE, glm::value_ptr(model.modelMatrix));
			glNamedBufferSubData(materialBuffer, 0, sizeof(Material), &model.material);
			glBindVertexArray(model.vertexArray);
			glUseProgram(shadowShaderProgram);
			glDrawArrays(GL_TRIANGLES, 0, model.vertexCount);
		}
	}

	glBindFramebuffer(GL_FRAMEBUFFER, 0);

	glm::mat4 biasMatrix(
		0.5, 0.0, 0.0, 0.0,
		0.0, 0.5, 0.0, 0.0,
		0.0, 0.0, 0.5, 0.0,
		0.5, 0.5, 0.5, 1.0
		);

	shadowViewProjectionMatrixIndex = glGetUniformLocation(shaderProgram, "shadowViewProjectionMatrix");
	shadowBiasMatrixIndex = glGetUniformLocation(shaderProgram, "shadowBiasMatrix");
	glProgramUniformMatrix4fv(shaderProgram, shadowViewProjectionMatrixIndex, 2, GL_FALSE, glm::value_ptr(depthViewProjectionMatrices[0]));
	glProgramUniformMatrix4fv(shaderProgram, shadowBiasMatrixIndex, 1, GL_FALSE, glm::value_ptr(biasMatrix));
}
Exemplo n.º 3
0
bool IMaterial::FrameBufferInit()
{
    GLint viewport[4];
    
    glGetIntegerv(GL_VIEWPORT, viewport);
    
    m_fViewportWidth = viewport[2];
    m_fViewportHeight = viewport[3];
    
    glGenFramebuffers(1, &m_gFB);
    glBindFramebuffer(GL_FRAMEBUFFER, m_gFB);
    
    glGenTextures(1, &m_gMainTexFrameBuffer);
    glBindTexture(GL_TEXTURE_2D, m_gMainTexFrameBuffer);
    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_RGBA, m_fViewportWidth, m_fViewportHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
//    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_gMainTexFrameBuffer, 0);
    glBindTexture(GL_TEXTURE_2D, 0);
    
    glGenRenderbuffers(1, &m_gRB);
    glBindRenderbuffer(GL_RENDERBUFFER, m_gRB);
    glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA8_OES, m_fViewportWidth, m_fViewportHeight);
    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, m_gRB);
    
    glGenRenderbuffers(1, &m_gRBDepth);
    glBindRenderbuffer(GL_RENDERBUFFER, m_gRBDepth);
    glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, m_fViewportWidth, m_fViewportHeight);
    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, m_gRBDepth);
    glBindRenderbuffer(GL_RENDERBUFFER, 0);
    
    

//    glEnable(GL_DEPTH_TEST);
//    glDepthFunc(GL_LESS);
//    glDepthMask(GL_TRUE);
//    glDepthRangef(0.0f, 1.0f);
//    glClearDepthf(1.0f);
    glClearColor(1.0f, 0.0f, 0.0f, 1.0f);


    if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
    {
        __LOG("Faild to create frame buffer");
        
        return false;
    }
    
    glGenVertexArraysOES(1, &m_gVAO);
    glBindVertexArrayOES(m_gVAO);
    
    glGenBuffers(1, &m_gVBO);
    glBindBuffer(GL_ARRAY_BUFFER, m_gVBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(quad), quad, GL_STATIC_DRAW);
    glEnableVertexAttribArray(SAL_POSITION);
    glVertexAttribPointer(SAL_POSITION, 3, GL_FLOAT, GL_FALSE, sizeof(float_t) * 5, 0);
    glEnableVertexAttribArray(SAL_TEXTURE_COORD);
    glVertexAttribPointer(SAL_TEXTURE_COORD, 2, GL_FLOAT, GL_FALSE, sizeof(float_t) * 5, (char*)NULL + (sizeof(float_t) * 3));
    
    glBindVertexArrayOES(0);
    

    glBindFramebuffer(GL_FRAMEBUFFER, Globals::GetDefaultFramebuffer());
    //glBindFramebuffer(GL_FRAMEBUFFER, m_gFB);

    return true;
}
Exemplo n.º 4
0
/**
 * Create a new texture in the backend renderer
 * @param active_texture_unit Active texture unit to bind to for creation
 * @param cache_entry CacheEntry to create texture for
 * @param raw_data Raw texture data
 * @return a pointer to CacheEntry::BackendData with renderer-specific texture data
 */
TextureManager::CacheEntry::BackendData* TextureInterface::Create(int active_texture_unit, 
    const TextureManager::CacheEntry& cache_entry, u8* raw_data) {

    BackendData* backend_data = new BackendData();

    glActiveTexture(GL_TEXTURE0 + active_texture_unit);

    switch (cache_entry.type_) {

    // Normal texture from RAM
    case TextureManager::kSourceType_Normal:
        glGenTextures(1, &backend_data->color_texture_);    
        glBindTexture(GL_TEXTURE_2D, backend_data->color_texture_);
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, cache_entry.width_, cache_entry.height_, 0, 
            GL_RGBA, GL_UNSIGNED_BYTE, raw_data);
        break;

    // Texture is the result of an EFB copy
    case TextureManager::kSourceType_EFBCopy:
        {
            GLuint textures[2];
            glGenTextures(2, textures);  

            backend_data->color_texture_ = textures[0];
            backend_data->depth_texture_ = textures[1];
            backend_data->is_depth_copy = (cache_entry.efb_copy_data_.pixel_format_ == gp::kPixelFormat_Z24);

            // Create the color component texture
            glBindTexture(GL_TEXTURE_2D, backend_data->color_texture_);
            glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, cache_entry.width_, cache_entry.height_, 0, 
                GL_RGBA, GL_UNSIGNED_BYTE, NULL);
            glBindTexture(GL_TEXTURE_2D, 0);
        
            // Create the depth component texture
            glBindTexture(GL_TEXTURE_2D, backend_data->depth_texture_);
            glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, cache_entry.width_, 
                cache_entry.height_, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, NULL);
            glBindTexture(GL_TEXTURE_2D, 0);
        
            // Create the FBO and attach color/depth textures
            glGenFramebuffers(1, &backend_data->efb_framebuffer_); // Generate framebuffer
            glBindFramebuffer(GL_DRAW_FRAMEBUFFER, backend_data->efb_framebuffer_);

            glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 
                backend_data->color_texture_, 0);
            glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 
                backend_data->depth_texture_, 0);
        
            // Check for completeness
            GLenum res = glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER);
            _ASSERT_MSG(TGP, GL_FRAMEBUFFER_COMPLETE == res, "couldn't OpenGL EFB copy FBO!");

            //////////////////////

            /*glBindFramebuffer(GL_READ_FRAMEBUFFER, backend_data->efb_framebuffer_);
            glReadBuffer(GL_COLOR_ATTACHMENT0);

            static u8 raw_data[1024 * 1024 * 4];
            static int num = 0;
            num++;
            glBindFramebuffer(GL_READ_FRAMEBUFFER, parent_->fbo_[RendererBase::kFramebuffer_EFB]);
            glReadBuffer(GL_DEPTH_ATTACHMENT); 
            glReadPixels(0,0, cache_entry.width_, cache_entry.height_, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, raw_data);

            // Optionally dump texture to TGA...
            if (1) {
                std::string filepath = common::g_config->program_dir() + std::string("/dump/efb-copies/");
                common::CreateFullPath(filepath);
                filepath = common::FormatStr("%s/%08x_%d.tga", filepath.c_str(), gp::g_bp_regs.efb_copy_addr << 5, num);
                video_core::DumpTGA(filepath, cache_entry.width_, cache_entry.height_, raw_data);
            }
            glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
            */
            //////////////////////////////

            // Rebind EFB
            glBindFramebuffer(GL_DRAW_FRAMEBUFFER, parent_->fbo_[RendererBase::kFramebuffer_EFB]);
        }

        break;

    // Unknown texture source
    default:
        _ASSERT_MSG(TGP, 0, "Unknown texture source %d", (int)cache_entry.type_);
        break;

    }
    return backend_data;
}
Exemplo n.º 5
0
// The MAIN function, from here we start our application and run our Game loop
int main()
{
    // Init GLFW
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

    GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", nullptr, nullptr); // Windowed
    glfwMakeContextCurrent(window);

    // Set the required callback functions
    glfwSetKeyCallback(window, key_callback);
    glfwSetCursorPosCallback(window, mouse_callback);
    glfwSetScrollCallback(window, scroll_callback);

    // Options
    glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);

    // Initialize GLEW to setup the OpenGL Function pointers
    glewExperimental = GL_TRUE;
    glewInit();

    // Define the viewport dimensions
    glViewport(0, 0, SCR_WIDTH, SCR_HEIGHT);

    // Setup some OpenGL options
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);

    // Setup and compile our shaders
    Shader shader("point_shadows.vs", "point_shadows.frag");
    Shader simpleDepthShader("point_shadows_depth.vs", "point_shadows_depth.frag", "point_shadows_depth.gs");

    // Set texture samples
    shader.Use();
    glUniform1i(glGetUniformLocation(shader.Program, "diffuseTexture"), 0);
    glUniform1i(glGetUniformLocation(shader.Program, "depthMap"), 1);

    // Light source
    glm::vec3 lightPos(0.0f, 0.0f, 0.0f);

    // Load textures
    woodTexture = loadTexture(FileSystem::getPath("resources/textures/wood.png").c_str());

    // Configure depth map FBO
    const GLuint SHADOW_WIDTH = 1024, SHADOW_HEIGHT = 1024;
    GLuint depthMapFBO;
    glGenFramebuffers(1, &depthMapFBO);
    // Create depth cubemap texture
    GLuint depthCubemap;
    glGenTextures(1, &depthCubemap);
    glBindTexture(GL_TEXTURE_CUBE_MAP, depthCubemap);
    for (GLuint i = 0; i < 6; ++i)
        glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_DEPTH_COMPONENT, SHADOW_WIDTH, SHADOW_HEIGHT, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
    // Attach cubemap as depth map FBO's color buffer
    glBindFramebuffer(GL_FRAMEBUFFER, depthMapFBO);
    glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, depthCubemap, 0);
    glDrawBuffer(GL_NONE);
    glReadBuffer(GL_NONE);
    if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
        std::cout << "Framebuffer not complete!" << std::endl;
    glBindFramebuffer(GL_FRAMEBUFFER, 0);

    glClearColor(0.1f, 0.1f, 0.1f, 1.0f);

    // Game loop
    while (!glfwWindowShouldClose(window))
    {
        // Set frame time
        GLfloat currentFrame = glfwGetTime();
        deltaTime = currentFrame - lastFrame;
        lastFrame = currentFrame;

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

        // Move light position over time
        //lightPos.z = sin(glfwGetTime() * 0.5) * 3.0;

        // 0. Create depth cubemap transformation matrices
        GLfloat aspect = (GLfloat)SHADOW_WIDTH / (GLfloat)SHADOW_HEIGHT;
        GLfloat near = 1.0f;
        GLfloat far = 25.0f;
        glm::mat4 shadowProj = glm::perspective(90.0f, aspect, near, far);
        std::vector<glm::mat4> shadowTransforms;
        shadowTransforms.push_back(shadowProj * glm::lookAt(lightPos, lightPos + glm::vec3( 1.0,  0.0,  0.0), glm::vec3(0.0, -1.0,  0.0)));
        shadowTransforms.push_back(shadowProj * glm::lookAt(lightPos, lightPos + glm::vec3(-1.0,  0.0,  0.0), glm::vec3(0.0, -1.0,  0.0)));
        shadowTransforms.push_back(shadowProj * glm::lookAt(lightPos, lightPos + glm::vec3( 0.0,  1.0,  0.0), glm::vec3(0.0,  0.0,  1.0)));
        shadowTransforms.push_back(shadowProj * glm::lookAt(lightPos, lightPos + glm::vec3( 0.0, -1.0,  0.0), glm::vec3(0.0,  0.0, -1.0)));
        shadowTransforms.push_back(shadowProj * glm::lookAt(lightPos, lightPos + glm::vec3( 0.0,  0.0,  1.0), glm::vec3(0.0, -1.0,  0.0)));
        shadowTransforms.push_back(shadowProj * glm::lookAt(lightPos, lightPos + glm::vec3( 0.0,  0.0, -1.0), glm::vec3(0.0, -1.0,  0.0)));

        // 1. Render scene to depth cubemap
        glViewport(0, 0, SHADOW_WIDTH, SHADOW_HEIGHT);
        glBindFramebuffer(GL_FRAMEBUFFER, depthMapFBO);
        glClear(GL_DEPTH_BUFFER_BIT);
        simpleDepthShader.Use();
        for (GLuint i = 0; i < 6; ++i)
            glUniformMatrix4fv(glGetUniformLocation(simpleDepthShader.Program, ("shadowTransforms[" + std::to_string(i) + "]").c_str()), 1, GL_FALSE, glm::value_ptr(shadowTransforms[i]));
        glUniform1f(glGetUniformLocation(simpleDepthShader.Program, "far_plane"), far);
        glUniform3fv(glGetUniformLocation(simpleDepthShader.Program, "lightPos"), 1, &lightPos[0]);
        RenderScene(simpleDepthShader);
        glBindFramebuffer(GL_FRAMEBUFFER, 0);

        // 2. Render scene as normal
        glViewport(0, 0, SCR_WIDTH, SCR_HEIGHT);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        shader.Use();
        glm::mat4 projection = glm::perspective(camera.Zoom, (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f);
        glm::mat4 view = camera.GetViewMatrix();
        glUniformMatrix4fv(glGetUniformLocation(shader.Program, "projection"), 1, GL_FALSE, glm::value_ptr(projection));
        glUniformMatrix4fv(glGetUniformLocation(shader.Program, "view"), 1, GL_FALSE, glm::value_ptr(view));
        // Set light uniforms
        glUniform3fv(glGetUniformLocation(shader.Program, "lightPos"), 1, &lightPos[0]);
        glUniform3fv(glGetUniformLocation(shader.Program, "viewPos"), 1, &camera.Position[0]);
        // Enable/Disable shadows by pressing 'SPACE'
        glUniform1i(glGetUniformLocation(shader.Program, "shadows"), shadows);
        glUniform1f(glGetUniformLocation(shader.Program, "far_plane"), far);
        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, woodTexture);
        glActiveTexture(GL_TEXTURE1);
        glBindTexture(GL_TEXTURE_CUBE_MAP, depthCubemap);
        RenderScene(shader);

        // Swap the buffers
        glfwSwapBuffers(window);
    }

    glfwTerminate();
    return 0;
}
Exemplo n.º 6
0
void GraphicsContext3D::reshape(int width, int height)
{
    if ((width == m_currentWidth && height == m_currentHeight) || (!m_private))
        return;

    m_currentWidth = width;
    m_currentHeight = height;

    makeContextCurrent();

    // Create color buffer
    glBindTexture(GraphicsContext3D::TEXTURE_2D, m_texture);
    if (m_attrs.alpha)
        glTexImage2D(GraphicsContext3D::TEXTURE_2D, /* level */ 0, GraphicsContext3D::RGBA, width, height, /* border */ 0, GraphicsContext3D::RGBA, GraphicsContext3D::UNSIGNED_BYTE, /* data */ 0);
    else
        glTexImage2D(GraphicsContext3D::TEXTURE_2D, /* level */ 0, GraphicsContext3D::RGB, width, height, /* border */ 0, GraphicsContext3D::RGB, GraphicsContext3D::UNSIGNED_BYTE, /* data */ 0);
    glBindTexture(GraphicsContext3D::TEXTURE_2D, 0);

    // Create depth and stencil buffers.
#if defined(QT_OPENGL_ES_2)
    if (m_attrs.depth) {
        glBindRenderbuffer(GraphicsContext3D::RENDERBUFFER, m_depthBuffer);
        glRenderbufferStorage(GraphicsContext3D::RENDERBUFFER, GraphicsContext3D::DEPTH_COMPONENT16, width, height);
        glBindRenderbuffer(GraphicsContext3D::RENDERBUFFER, 0);
    }
    if (m_attrs.stencil) {
        glBindRenderbuffer(GraphicsContext3D::RENDERBUFFER, m_stencilBuffer);
        glRenderbufferStorage(GraphicsContext3D::RENDERBUFFER, GraphicsContext3D::STENCIL_INDEX8, width, height);
        glBindRenderbuffer(GraphicsContext3D::RENDERBUFFER, 0);
    }
#else
    if (m_attrs.depth || m_attrs.stencil) {
        glBindRenderbuffer(GraphicsContext3D::RENDERBUFFER, m_depthStencilBuffer);
        if (m_attrs.depth && m_attrs.stencil)
            glRenderbufferStorage(GraphicsContext3D::RENDERBUFFER, GL_DEPTH24_STENCIL8, width, height);
        else if (m_attrs.depth)
            glRenderbufferStorage(GraphicsContext3D::RENDERBUFFER, GraphicsContext3D::DEPTH_COMPONENT, width, height);
        else if (m_attrs.stencil)
            glRenderbufferStorage(GraphicsContext3D::RENDERBUFFER, GraphicsContext3D::STENCIL_INDEX, width, height);
        glBindRenderbuffer(GraphicsContext3D::RENDERBUFFER, 0);
    }
#endif

    // Construct canvas FBO.
    glBindFramebuffer(GraphicsContext3D::FRAMEBUFFER, m_fbo);
    glFramebufferTexture2D(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::COLOR_ATTACHMENT0, GraphicsContext3D::TEXTURE_2D, m_texture, 0);
#if defined(QT_OPENGL_ES_2)
    if (m_attrs.depth)
        glFramebufferRenderbuffer(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::DEPTH_ATTACHMENT, GraphicsContext3D::RENDERBUFFER, m_depthBuffer);
    if (m_attrs.stencil)
        glFramebufferRenderbuffer(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::STENCIL_ATTACHMENT, GraphicsContext3D::RENDERBUFFER, m_stencilBuffer);
#else
    if (m_attrs.depth && m_attrs.stencil)
        glFramebufferRenderbuffer(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::DEPTH_STENCIL_ATTACHMENT, GraphicsContext3D::RENDERBUFFER, m_depthStencilBuffer);
    else if (m_attrs.depth)
        glFramebufferRenderbuffer(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::DEPTH_ATTACHMENT, GraphicsContext3D::RENDERBUFFER, m_depthStencilBuffer);
    else if (m_attrs.stencil)
        glFramebufferRenderbuffer(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::STENCIL_ATTACHMENT, GraphicsContext3D::RENDERBUFFER, m_depthStencilBuffer);
#endif

    GLenum status = glCheckFramebufferStatus(GraphicsContext3D::FRAMEBUFFER);
    if (status != GraphicsContext3D::FRAMEBUFFER_COMPLETE) {
        LOG_ERROR("GraphicsContext3D: Canvas FBO initialization failed.");
        return;
    }

    int clearFlags = GraphicsContext3D::COLOR_BUFFER_BIT;
    if (m_attrs.depth)
        clearFlags |= GraphicsContext3D::DEPTH_BUFFER_BIT;
    if (m_attrs.stencil)
        clearFlags |= GraphicsContext3D::STENCIL_BUFFER_BIT;

    glClear(clearFlags);
    glFlush();
}
void init()
{
    //std::string racineProjet = "C:/Users/etu/workspace/code/Rendu temps reel/";
    std::string racineProjet = "C:/Users/etu/Documents/GitHub/Gamagora-Rendu_temps_reel-TP/";
    //std::string racineProjet = "B:/Utilisateur/git/code/Gamagora-Rendu_temps_reel-TP/";

	// Build our program and an empty VAO
    gs.programView = buildProgram((racineProjet+(std::string)"basic.vsl").c_str(), (racineProjet+(std::string)"basic.fsl").c_str());


    Mesh m;
    m = ObjManager::loadFromOBJ(Vector3D(0,0,0), (racineProjet+(std::string)"monkey.obj").c_str());

    nbVertex = m.nbface()+6; //nbface + quad "sol"

    float* data = (float*) malloc(nbVertex*4*sizeof(float));
	float* dataNormal = (float*) malloc(nbVertex * 4 * sizeof(float));

    std::vector<Vector3D> vertex = m.getvertex();
    std::vector<int> face = m.getface();
    std::vector<Vector3D> normals = m.getNormals();
    std::vector<int> normalIds = m.getNormalIds();

    int i=0;
    for(int j=0; j<face.size(); j++){
        //set vertex
        data[i] = vertex[face[j]].x;
        data[i+1] = vertex[face[j]].y;
        data[i+2] = vertex[face[j]].z;
        data[i+3] = 1;



        dataNormal[i] = normals[normalIds[j]].x;
        dataNormal[i+1] = normals[normalIds[j]].y;
        dataNormal[i+2] = normals[normalIds[j]].z;
        dataNormal[i+3] = 1;

        i+=4;
    }

    //ajout du quad pour faire le sol
    ajoutSol(Vector3D(-15,-1,-15), Vector3D(15,-1,-15), Vector3D(15,-1,15), Vector3D(-15,-1,15), Vector3D(0,1,0),
                  nbVertex*4, data, dataNormal);



	GLuint buffer;
    glGenBuffers(1, &buffer);
    glBindBuffer(GL_ARRAY_BUFFER, buffer);
    glBufferData(GL_ARRAY_BUFFER, nbVertex*4*4, data, GL_STATIC_DRAW);

    GLuint buffer2;
    glGenBuffers(1, &buffer2);
    glBindBuffer(GL_ARRAY_BUFFER, buffer2);
    glBufferData(GL_ARRAY_BUFFER, nbVertex*4*4, dataNormal, GL_STATIC_READ);

	glCreateVertexArrays(1, &gs.vao);

	glBindVertexArray(gs.vao);

        glBindBuffer(GL_ARRAY_BUFFER, buffer);
        glVertexAttribPointer(12, 4, GL_FLOAT, GL_FALSE, 0, 0);
		glEnableVertexAttribArray(12);

        glBindBuffer(GL_ARRAY_BUFFER, buffer2);
        glVertexAttribPointer(13, 4, GL_FLOAT, GL_FALSE, 0, 0);
        glEnableVertexAttribArray(13);

    glBindVertexArray(0);

    glEnable(GL_DEPTH_TEST);

    // create the depth texture
    glGenTextures(1, &gs.depthTexture);
    glBindTexture(GL_TEXTURE_2D, gs.depthTexture);
	glTexStorage2D(GL_TEXTURE_2D, 1, GL_DEPTH_COMPONENT32F, 640, 480);

    // Framebuffer
    glGenFramebuffers(1, &gs.fbo);
    glBindFramebuffer(GL_FRAMEBUFFER, gs.fbo);
    glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, gs.depthTexture, 0);    

    assert(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE);
    glBindFramebuffer(GL_FRAMEBUFFER, 0);

	glActiveTexture(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_2D, gs.depthTexture);

	glBindVertexArray(0);
	free(data); free(dataNormal);
}
Exemplo n.º 8
0
int DemoApplication::OnInit()
{
    std::cout << "DEMO APP INITIALIZED\n";


    // framebuffer generation
    glGenFramebuffers(1, &fbo);
    glBindFramebuffer(GL_FRAMEBUFFER, fbo);

    glGenTextures(1, &fboTexture);
    glBindTexture(GL_TEXTURE_2D, fboTexture);
    glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA8, 512, 512);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, fboTexture, 0);

    GLenum drawBuffers[] = { GL_COLOR_ATTACHMENT0 };
    glDrawBuffers(1, drawBuffers);

    glGenRenderbuffers(1, &fboDepth);
    glBindRenderbuffer(GL_RENDERBUFFER, fboDepth);
    glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, 512, 512);
    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, fboDepth);

    GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
    if (status != GL_FRAMEBUFFER_COMPLETE)
    {
        printf("Framebuffer Error\n");
    }
    glBindFramebuffer(GL_FRAMEBUFFER, 0);

    // mesh data generation

    float vertexData[] =
    {
        // Position			UV Coords
        //	X,  Y,  Z,  W, | S, T
        -5, 0,  -5,  1,  0, 0,
        5,  0,  -5,  1,  1, 0,
        5,  10, -5,  1,  1, 1,
        -5, 10, -5,  1,  0, 1,
    };

    unsigned int indexData[] =
    {
        0,1,2,
        0,2,3,
    };

    // VAO-begin - will store handles to the VBO and IBO and make them available when bound
    glGenVertexArrays(1, &temp.m_VAO);
    glBindVertexArray(temp.m_VAO);

    // VBO - describes vertex data
    glGenBuffers(1, &temp.m_VBO);
    glBindBuffer(GL_ARRAY_BUFFER, temp.m_VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 6 * 4, vertexData, GL_STATIC_DRAW);

    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(float) * 6, 0);
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 6, (void*)(sizeof(float) * 4));

    // IBO - order to draw verticies
    glGenBuffers(1, &temp.m_IBO);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, temp.m_IBO);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int) * 6, indexData, GL_STATIC_DRAW);

    // VAO-end
    glBindVertexArray(0);						// VAO comes first! important!
    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

    // shader program generation
    // TODO: load these shaders from file

    const char* vsSource = "#version 410\n \
							layout(location=0) in vec4 Position;\
							layout(location=1) in vec2 TexCoord;\
							out vec2 vTexCoord;\
							uniform mat4 ProjectionView;\
							void main()\
							{\
								vTexCoord = TexCoord;\
								gl_Position = ProjectionView * Position;\
							}";
Exemplo n.º 9
0
  bool CreateFramebuffer(int width, int height, Framebuffer& framebuffer) {
    framebuffer.bo = gbm_bo_create(gbm_, width, height, GBM_FORMAT_XRGB8888,
                                   GBM_BO_USE_SCANOUT | GBM_BO_USE_RENDERING);
    if (!framebuffer.bo) {
      fprintf(stderr, "failed to create a gbm buffer.\n");
      return false;
    }

    framebuffer.fd = gbm_bo_get_fd(framebuffer.bo);
    if (framebuffer.fd < 0) {
      fprintf(stderr, "failed to get fb for bo: %d", framebuffer.fd);
      return false;
    }

    uint32_t handle = gbm_bo_get_handle(framebuffer.bo).u32;
    uint32_t stride = gbm_bo_get_stride(framebuffer.bo);
    uint32_t offset = 0;
    drmModeAddFB2(drm_->GetFD(), width, height, GBM_FORMAT_XRGB8888, &handle,
                  &stride, &offset, &framebuffer.fb_id, 0);
    if (!framebuffer.fb_id) {
      fprintf(stderr, "failed to create framebuffer from buffer object.\n");
      return false;
    }

    const EGLint khr_image_attrs[] = {EGL_DMA_BUF_PLANE0_FD_EXT,
                                      framebuffer.fd,
                                      EGL_WIDTH,
                                      width,
                                      EGL_HEIGHT,
                                      height,
                                      EGL_LINUX_DRM_FOURCC_EXT,
                                      GBM_FORMAT_XRGB8888,
                                      EGL_DMA_BUF_PLANE0_PITCH_EXT,
                                      static_cast<const int>(stride),
                                      EGL_DMA_BUF_PLANE0_OFFSET_EXT,
                                      static_cast<const int>(offset),
                                      EGL_NONE};

    framebuffer.image =
        egl_.CreateImageKHR(egl_.display, EGL_NO_CONTEXT, EGL_LINUX_DMA_BUF_EXT,
                            nullptr /* no client buffer */, khr_image_attrs);
    if (framebuffer.image == EGL_NO_IMAGE_KHR) {
      fprintf(stderr, "failed to make image from buffer object: %s\n",
              EglGetError());
      return false;
    }

    glGenTextures(1, &framebuffer.gl_tex);
    glBindTexture(GL_TEXTURE_2D, framebuffer.gl_tex);
    egl_.EGLImageTargetTexture2DOES(GL_TEXTURE_2D, framebuffer.image);
    glBindTexture(GL_TEXTURE_2D, 0);

    glGenFramebuffers(1, &framebuffer.gl_fb);
    glBindFramebuffer(GL_FRAMEBUFFER, framebuffer.gl_fb);
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
                           framebuffer.gl_tex, 0);

    if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
      fprintf(stderr,
              "failed framebuffer check for created target buffer: %x\n",
              glCheckFramebufferStatus(GL_FRAMEBUFFER));
      glDeleteFramebuffers(1, &framebuffer.gl_fb);
      glDeleteTextures(1, &framebuffer.gl_tex);
      return false;
    }

    return true;
  }
Exemplo n.º 10
0
void RenderTarget::Activate()
{
	glBindFramebuffer(GL_FRAMEBUFFER, fbo);

	if (targets.size())
	{
		glDrawBuffers(targets.size(), buffers);
		for (size_t i = 0; i < targets.size(); i++)
		{
			targets[i]->SetAsAttachment(i);
		}
	}

	if (cvx != vx || cvy != vy || cvw != vw || cvh != vh)
	{
		cvx = vx;
		cvy = vy;
		cvw = vw;
		cvh = vh;
		glViewport(vx, vy, vw, vh);
	}

	int err = glCheckFramebufferStatus(GL_FRAMEBUFFER);
	switch(err)
	{
	case GL_FRAMEBUFFER_COMPLETE: break;
	case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: Fatal("GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT\n"); break;
	case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT:Fatal("GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS\n"); break;
	case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:Fatal("GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT\n"); break;
	case GL_FRAMEBUFFER_UNSUPPORTED:Fatal("GL_FRAMEBUFFER_UNSUPPORTED\n"); break;
	case GL_INVALID_FRAMEBUFFER_OPERATION:Fatal("GL_INVALID_FRAMEBUFFER_OPERATION\n"); break;
	case GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS_ARB:Fatal("GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS_ARB\n"); break;
	case GL_FRAMEBUFFER_INCOMPLETE_LAYER_COUNT_ARB:Fatal("GL_FRAMEBUFFER_INCOMPLETE_LAYER_COUNT_ARB\n"); break;
	default: Fatal("Unknown framebuffer error"); break;
	}

	if (depth)
	{
		glEnable(GL_DEPTH_TEST);
	}
	else
	{
		glDisable(GL_DEPTH_TEST);
	}

	static BlendMode currentBlendFunc = Overwrite;
	switch(blendmode)
	{
	case Overwrite:
		glDisable(GL_BLEND);
		break;
	case Alphablend:
		if (currentBlendFunc != Alphablend) 
		{
			currentBlendFunc = Alphablend;
			glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
		}
		glEnable(GL_BLEND);
		break;
	case Additive:
		if (currentBlendFunc != Additive) 
		{
			currentBlendFunc = Additive;
			glBlendFunc(GL_ONE, GL_ONE);
		}
		glEnable(GL_BLEND);
		break;
	}
}
Exemplo n.º 11
0
void
state_game_init(void *ptr)
{
	if(!world_is_initalized())
	{
		error("state_game started before world_init()");
		state_queue_fail();
		return;
	}

	pos = world_get_player();

	state_window_get_size(&windoww, &windowh);

	//load shaders 'n stuff
	gl_program_load_file(&drawprogram, "shaders/vs", "shaders/fs");
	gl_program_load_file(&ppprogram, "shaders/pvs", "shaders/pfs");

	modelmatrix = glGetUniformLocation(drawprogram, "MODEL");
	viewprojectionmatrix = glGetUniformLocation(drawprogram, "VP");
	postprocess_uniform_tex = glGetUniformLocation(ppprogram, "tex");
	postprocess_uniform_depth = glGetUniformLocation(ppprogram, "depth");
	postprocess_uniform_window_szie = glGetUniformLocation(ppprogram, "window_size");

	//generate the post processing framebuffer
	glGenFramebuffers(1, &renderbuffer.framebuffer);
	glBindFramebuffer(GL_FRAMEBUFFER, renderbuffer.framebuffer);

	glGenTextures(1, &renderbuffer.colorbuffer);
	glGenTextures(1, &renderbuffer.depthbuffer);

	glBindTexture(GL_TEXTURE_2D, renderbuffer.colorbuffer);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, windoww, windowh, 0, GL_RGB, GL_FLOAT, 0);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_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);

	glBindTexture(GL_TEXTURE_2D, renderbuffer.depthbuffer);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, windoww, windowh, 0, GL_DEPTH_COMPONENT, GL_FLOAT, 0);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_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);

	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, renderbuffer.colorbuffer, 0);
	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, renderbuffer.depthbuffer, 0);

	//put the textures in thr right spots
	glUseProgram(ppprogram);
	GLuint tex = glGetUniformLocation(ppprogram, "tex");
	GLuint depth = glGetUniformLocation(ppprogram, "depth");

	glUniform1i(tex, 0);
	glUniform1i(depth, 1);

	//generate the post processing mesh
	GLfloat mesh[] = {
		-1.0f, 1.0f,
		-1.0f, -1.0f,
		1.0f, -1.0f,
		1.0f, 1.0f,
		-1.0f, 1.0f,
		1.0f, -1.0f
	};

	glGenBuffers(1, &pppointbuffer);
	glBindBuffer(GL_ARRAY_BUFFER, pppointbuffer);
	glBufferData(GL_ARRAY_BUFFER, sizeof(mesh) * sizeof(GLfloat), mesh, GL_STATIC_DRAW);

	if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
		fail("Bad Framebuffer");


	rotx = 0;
	roty = 0;

	posptr = entity_pos_get_ptr(pos);
	vec3_t friction = {PLAYER_FRICTION,PLAYER_FRICTION,PLAYER_FRICTION};
	entity_friction_set(pos, friction);
	state_mouse_center();
	SDL_ShowCursor(0);

	ticks = SDL_GetTicks();

	updatesem = SDL_CreateSemaphore(0);
	updatethread = SDL_CreateThread(updatethreadfunc, "updatethread", 0);

	textbox_fps = textbox_create(10, 10, 200, 100, "0fps", 0, TEXTBOX_FONT_ROBOTO_REGULAR, TEXTBOX_FONT_SIZE_MEDIUM, 0);
}
Exemplo n.º 12
0
	//--------------------------------------------------------------------------
	GBuffer::GBuffer(				unsigned int _width, 
									unsigned int _height)
	{
		// Initialize G-Buffer textures
		positionTex.Allocate(GL_RGBA32F,_width,_height);
		normalTex.Allocate(GL_RGBA16F,_width,_height);
		diffuseTex.Allocate(GL_RGBA16F,_width,_height);
		depthTex.Allocate(GL_DEPTH32F_STENCIL8,_width,_height);
		positionTex.SetWrapping(GL_CLAMP_TO_EDGE,GL_CLAMP_TO_EDGE);
		normalTex.SetWrapping(GL_CLAMP_TO_EDGE,GL_CLAMP_TO_EDGE);
		diffuseTex.SetWrapping(GL_CLAMP_TO_EDGE,GL_CLAMP_TO_EDGE);
		depthTex.SetWrapping(GL_CLAMP_TO_EDGE,GL_CLAMP_TO_EDGE);

		// Initialize framebuffer
		int outPosition			= 0;
		int outDiffuseSpecular	= 1;
		int outNormalRoughness	= 2;
		glGenFramebuffers(1, &framebuffer);
		glBindFramebuffer(GL_FRAMEBUFFER,framebuffer);

		// Attach output textures
		glFramebufferTexture2D(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT0 + outPosition, positionTex.target, positionTex.id, 0);
		glf::CheckFramebuffer(framebuffer);

		glBindTexture(diffuseTex.target,diffuseTex.id);
		glFramebufferTexture2D(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT0 + outDiffuseSpecular, diffuseTex.target, diffuseTex.id, 0);
		glf::CheckFramebuffer(framebuffer);
		
		glBindTexture(normalTex.target,normalTex.id);
		glFramebufferTexture2D(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT0 + outNormalRoughness, normalTex.target, normalTex.id, 0);
		glf::CheckFramebuffer(framebuffer);

		glBindTexture(depthTex.target,depthTex.id);
		glFramebufferTexture2D(GL_FRAMEBUFFER,GL_DEPTH_STENCIL_ATTACHMENT, depthTex.target, depthTex.id, 0);
		glf::CheckFramebuffer(framebuffer);

		GLenum drawBuffers[3] = {GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2};
		glDrawBuffers(3,drawBuffers);
		assert(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE);
		glBindFramebuffer(GL_FRAMEBUFFER, 0);


		// Program regular mesh
		ProgramOptions regularOptions = ProgramOptions::CreateVSOptions();
		regularOptions.AddDefine<int>("GBUFFER",				1);
		regularOptions.AddDefine<int>("OUT_POSITION",			outPosition);
		regularOptions.AddDefine<int>("OUT_DIFFUSE_SPECULAR",	outDiffuseSpecular);
		regularOptions.AddDefine<int>("OUT_NORMAL_ROUGHNESS",	outNormalRoughness);
		regularRenderer.program.Compile(regularOptions.Append(LoadFile(directory::ShaderDirectory + "meshregular.vs")),
										regularOptions.Append(LoadFile(directory::ShaderDirectory + "meshregular.fs")));

		regularRenderer.transformVar	= regularRenderer.program["Transform"].location;
		regularRenderer.modelVar		= regularRenderer.program["Model"].location;
		regularRenderer.diffuseTexUnit	= regularRenderer.program["DiffuseTex"].unit;
		regularRenderer.normalTexUnit	= regularRenderer.program["NormalTex"].unit;
		regularRenderer.roughnessVar	= regularRenderer.program["Roughness"].location;
		regularRenderer.specularityVar	= regularRenderer.program["Specularity"].location;

		glProgramUniform1i(regularRenderer.program.id, regularRenderer.program["DiffuseTex"].location, regularRenderer.diffuseTexUnit);
		glProgramUniform1i(regularRenderer.program.id, regularRenderer.program["NormalTex"].location,  regularRenderer.normalTexUnit);


		// Program terrain mesh
		ProgramOptions terrainOptions = ProgramOptions::CreateVSOptions();
		terrainOptions.AddDefine<int>("GBUFFER",				1);
		terrainOptions.AddDefine<int>("OUT_POSITION",			outPosition);
		terrainOptions.AddDefine<int>("OUT_DIFFUSE_SPECULAR",	outDiffuseSpecular);
		terrainOptions.AddDefine<int>("OUT_NORMAL_ROUGHNESS",	outNormalRoughness);
		terrainRenderer.program.Compile(terrainOptions.Append(LoadFile(directory::ShaderDirectory + "meshterrain.vs")),
										terrainOptions.Append(LoadFile(directory::ShaderDirectory + "meshterrain.cs")),
										terrainOptions.Append(LoadFile(directory::ShaderDirectory + "meshterrain.es")),
										terrainOptions.Append(LoadFile(directory::ShaderDirectory + "meshterrain.fs")));

		terrainRenderer.transformVar	= terrainRenderer.program["Transform"].location;
		terrainRenderer.diffuseTexUnit	= terrainRenderer.program["DiffuseTex"].unit;
		terrainRenderer.normalTexUnit	= terrainRenderer.program["NormalTex"].unit;
		terrainRenderer.heightTexUnit	= terrainRenderer.program["HeightTex"].unit;
		terrainRenderer.roughnessVar	= terrainRenderer.program["Roughness"].location;
		terrainRenderer.specularityVar	= terrainRenderer.program["Specularity"].location;

		terrainRenderer.tileSizeVar		= terrainRenderer.program["TileSize"].location;
		terrainRenderer.tileCountVar	= terrainRenderer.program["TileCount"].location;
		terrainRenderer.tileOffsetVar	= terrainRenderer.program["TileOffset"].location;
		terrainRenderer.projFactorVar	= terrainRenderer.program["ProjFactor"].location;
		terrainRenderer.tessFactorVar	= terrainRenderer.program["TessFactor"].location;
		terrainRenderer.heightFactorVar	= terrainRenderer.program["HeightFactor"].location;
		terrainRenderer.tileFactorVar	= terrainRenderer.program["TileFactor"].location;

		glProgramUniform1i(terrainRenderer.program.id, terrainRenderer.program["DiffuseTex"].location, terrainRenderer.diffuseTexUnit);
		glProgramUniform1i(terrainRenderer.program.id, terrainRenderer.program["NormalTex"].location,  terrainRenderer.normalTexUnit);
		glProgramUniform1i(terrainRenderer.program.id, terrainRenderer.program["HeightTex"].location,  terrainRenderer.heightTexUnit);

		glf::CheckError("GBuffer::GBuffer");
	}
Exemplo n.º 13
0
void Grid::initData()
{
	D = 2, Q = 9;
	demo = 0;
	//Input horizontal velocity
	vx = Settings::root["vx"].asFloat();
	//Input vertical velocity
	vy = Settings::root["vy"].asFloat();
	//Input density ρ = rho
	rho = Settings::root["rho"].asFloat();
	//Relaxation time τ = tau
	tau = Settings::root["tau"].asFloat();
	
	//Wrapping
	hWrap = Settings::root["wrap"]["horizontal"].asBool();
	vWrap = Settings::root["wrap"]["vertical"].asBool();
	
	lattice.resize(Q*num);
	solid.resize(2);
	for(int i=0; i<solid.size(); ++i)
	 solid[i].resize(num);
	
	float w0 = 4.f/9.f;
	float w1 = 1.f/9.f;
	float w2 = 1.f/36.f;
	
	float vSq = 1.5f*(vx*vx+vy*vy);
	
	//Fill lattice with equilibrium velocities
	for(int i=0; i<num; ++i)
	{
		int j=i*Q;
		lattice[j]	 = w0*rho*(1.f																			-vSq);
		lattice[j+1] = w1*rho*(1.f+3.f*vx				+4.5f*vx*vx							-vSq);
		lattice[j+2] = w1*rho*(1.f+3.f*vy				+4.5f*vy*vy							-vSq);
		lattice[j+3] = w1*rho*(1.f-3.f*vx				+4.5f*vx*vx							-vSq);
		lattice[j+4] = w1*rho*(1.f-3.f*vy				+4.5f*vy*vy							-vSq);
		lattice[j+5] = w2*rho*(1.f+3.f*( vx+vy)	+4.5f*( vx+vy)*( vx+vy)	-vSq);
		lattice[j+6] = w2*rho*(1.f+3.f*(-vx+vy)	+4.5f*(-vx+vy)*(-vx+vy)	-vSq);
		lattice[j+7] = w2*rho*(1.f+3.f*(-vx-vy)	+4.5f*(-vx-vy)*(-vx-vy)	-vSq);
		lattice[j+8] = w2*rho*(1.f+3.f*( vx-vy)	+4.5f*( vx-vy)*( vx-vy)	-vSq);
		solid[0][i] = false;
		solid[1][i] = true;
	}
	
	
	
	lSize = Q*num*sizeof(float);
	size_t size = num*sizeof(float);
	
	//create renderbuffer
	glGenRenderbuffers(1, &rendBuff);
	glBindRenderbuffer(GL_RENDERBUFFER, rendBuff);
	glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA32F, width, height);
	
	glGenFramebuffers(1, &frameBuff);
	glBindFramebuffer(GL_FRAMEBUFFER, frameBuff);
	glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, rendBuff);
	
	//Check renderbuffer completeness
	GLenum hey = glCheckFramebufferStatus(GL_FRAMEBUFFER);
	std::cout<<"Framebuffer:";
	switch(hey)
	{
		case GL_FRAMEBUFFER_COMPLETE:												std::cout<<"complete"; break;
		case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:					std::cout<<"incomplete attachment"; break;
		case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:	std::cout<<"incomplete missing attachment"; break;
		case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER:					std::cout<<"incomplete draw buffer"; break;
		default:																						std::cout<<"unknown"; break;
	}
	std::cout<<std::endl;
	glFinish();
	
	//Create OpenCL memory pointer for renderbuffer
	clVBOs.push_back(cl::BufferRenderGL(context, CL_MEM_READ_WRITE, rendBuff));
	
	clLattice.push_back(cl::Buffer(context, CL_MEM_WRITE_ONLY, lSize));
	clLattice.push_back(cl::Buffer(context, CL_MEM_WRITE_ONLY, lSize));
	clVelMag = cl::Buffer(context, CL_MEM_WRITE_ONLY, size);
	for(int i=0; i<solid.size(); ++i)
	 clSolid.push_back(cl::Buffer(context, CL_MEM_WRITE_ONLY, num*sizeof(char)));
	
	try
	{
		//Lattice can be copied to both memory locations for debugging
		//queue.enqueueWriteBuffer(clLattice[0], CL_TRUE, 0, lSize, &lattice[0], NULL, &event);
		queue.enqueueWriteBuffer(clLattice[1], CL_TRUE, 0, lSize, &lattice[0], NULL, &event);
		for(int i=0; i<solid.size(); i++)
		 queue.enqueueWriteBuffer(clSolid[i], CL_TRUE, 0, num*sizeof(char), &(solid[i])[0], NULL, &event);
		queue.finish();
	}
	catch(cl::Error e)
	{
		cluErr("Grid: initData", e);
	}
	
	//init kernels
	try
	{
		
		clStream = cl::Kernel(program, "stream");
		clHWrap = cl::Kernel(program, "hWrap");
		clVWrap = cl::Kernel(program, "vWrap");
		clSolidBB = cl::Kernel(program, "solidBB");
		clInflow = cl::Kernel(program, "inflow");
		clCollide = cl::Kernel(program, "collide");
		clRender = cl::Kernel(program, "render");
		
	}
	catch(cl::Error e)
	{
		cluErr("Grid: initData", e);
	}
	
	try
	{
		//Set constant arguments for each kernel
		clStream.setArg(2, width);
		clStream.setArg(3, height);
		
		clHWrap.setArg(1, width);
		clHWrap.setArg(2, height);
		clVWrap.setArg(1, width);
		clVWrap.setArg(2, height);
		
		clSolidBB.setArg(2, width);
		
		clInflow.setArg(1, vx);
		clInflow.setArg(2, vy);
		clInflow.setArg(3, rho);
		clInflow.setArg(4, width);
		
		clCollide.setArg(1, clVelMag);
		clCollide.setArg(2, width);
		clCollide.setArg(3, tau);
		
		clRender.setArg(0, clVelMag);
		clRender.setArg(2, width);
		clRender.setArg(3, height);
		clRender.setArg(4, vx);
		clRender.setArg(5, vy);
		clRender.setArg(6, clVBOs[0]);
		
		queue.finish();
	}
	catch(cl::Error e)
	{
		cluErr("Grid: initData", e);
	}
	
	//Set framebuffer addressing for blitting at the end of rendering
	glBindFramebuffer(GL_READ_FRAMEBUFFER, frameBuff);
	glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
}
Exemplo n.º 14
0
void RenderTarget::Initialize(mathfu::vec2i dimensions, GLenum format,
                              bool create_depth_buffer) {
  assert(!initialized());
  dimensions_ = dimensions;
  // Set up the framebuffer itself:
  framebuffer_id_ = 0;
  depth_buffer_id_ = 0;

  // Our framebuffer object:
  GL_CALL(glGenFramebuffers(1, &framebuffer_id_));

  // The texture we're going to render to
  GL_CALL(glGenTextures(1, &rendered_texture_id_));

  // Bind the framebuffer:
  GL_CALL(glBindFramebuffer(GL_FRAMEBUFFER, framebuffer_id_));

  // Set up the texture:
  GL_CALL(glBindTexture(GL_TEXTURE_2D, rendered_texture_id_));

  // Give an empty image to OpenGL.  (It will allocate memory, but not bother
  // to populate it.  Which is fine, since we're going to render into it.)
  GL_CALL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, dimensions.x(),
                       dimensions.y(), 0, GL_RGBA, format, nullptr));

  // Define texture properties:
  GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR));
  GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR));

  GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE));
  GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE));

  // Attach our texture as the color attachment.
  GL_CALL(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
                                 GL_TEXTURE_2D, rendered_texture_id_, 0));

  if (create_depth_buffer) {
    // A renderbuffer, that we'll use for depth:
    GL_CALL(glGenRenderbuffers(1, &depth_buffer_id_));

    // Bind renderbuffer and set it as the depth buffer:
    GL_CALL(glBindRenderbuffer(GL_RENDERBUFFER, depth_buffer_id_));
    GL_CALL(glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16,
                                  dimensions_.x(), dimensions_.y()));

    // Attach renderbuffer as our depth attachment.
    GL_CALL(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
                                      GL_RENDERBUFFER, depth_buffer_id_));
  }

  // Make sure everything worked:
  if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
    assert(false);
  }
  assert(framebuffer_id_ != 0);
  assert(depth_buffer_id_ != 0);

  // Be good citizens and clean up:
  // Bind the framebuffer:
  GL_CALL(glBindTexture(GL_TEXTURE_2D, 0));
  GL_CALL(glBindRenderbuffer(GL_RENDERBUFFER, 0));
  GL_CALL(glBindFramebuffer(GL_FRAMEBUFFER, 0));

  initialized_ = true;
}
Exemplo n.º 15
0
Renderer::Renderer(Window &parent) : OGLRenderer(parent) {
	camera = new Camera(-30.0f, 180.0f, Vector3(0.0f, -1500.0f, 0.0f));
	quad = Mesh::GenerateQuad();
	quad_corner = Mesh::GenerateQuad();

	heightMap = new HeightMap(TEXTUREDIR"terrain.raw");
	heightMap->SetTexture(SOIL_load_OGL_texture(TEXTUREDIR"BarrenReds.JPG", SOIL_LOAD_AUTO, SOIL_CREATE_NEW_ID, SOIL_FLAG_MIPMAPS));

	sceneShader = new Shader(SHADERDIR"Test_03_TexturedVertex.glsl", SHADERDIR"Test_03_TexturedFragment.glsl");
	bool sceneFlag = sceneShader->LinkProgram();

	combineShader = new Shader(SHADERDIR"Test_03_TexturedVertex.glsl", SHADERDIR"Test_10_ProcessFragment.glsl");
	bool combFlag = combineShader->LinkProgram();

	if (!combineShader->LinkProgram() || !sceneShader->LinkProgram() || !heightMap->GetTexture()) {
		return;
	}

	SetTextureRepeating(heightMap->GetTexture(), true);

	// scene depth texture
	glGenTextures(1, &bufferDepthTex);
	glBindTexture(GL_TEXTURE_2D, bufferDepthTex);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH24_STENCIL8, width, height, 0, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, NULL);

	// colour texture
	for (int i = 0; i < 2; ++i) {
		glGenTextures(1, &bufferColourTex[i]);
		glBindTexture(GL_TEXTURE_2D, bufferColourTex[i]);
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
	}

	glGenTextures(1, &debugColorTex);
	glBindTexture(GL_TEXTURE_2D, debugColorTex);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 800, 600, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);

	// set up buffer for scene rendering and post processing
	glGenFramebuffers(1, &bufferFBO);
	glGenFramebuffers(1, &processFBO);
	glGenFramebuffers(1, &debugbufferFBO);

	glBindFramebuffer(GL_FRAMEBUFFER, bufferFBO);
	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, bufferDepthTex, 0);
	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, bufferDepthTex, 0);
	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, bufferColourTex[0], 0);

	if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE || !bufferDepthTex || !bufferColourTex[0]) {
		return;
	}

	glBindFramebuffer(GL_FRAMEBUFFER, 0);
	glEnable(GL_DEPTH_TEST);
	init = true;
}
Exemplo n.º 16
0
Arquivo: map.cpp Projeto: psde/GBH
Map::Map(const char *map, Style* style){
	this->style = style;

	Filereader* reader = new Filereader(map);

	Chunk *animation_data;
	Chunk *dmap_data;

	Chunk *chk;
	while((chk = reader->getNextChunk())){
		if(strncmp(chk->header->type,"ANIM",4) == 0) {
			animation_data = chk;
		}
		if(strncmp(chk->header->type,"DMAP",4) == 0) {
			dmap_data = chk;
		}
	}

	// Read animation data
	char* starting = animation_data->data;
	char* offset = animation_data->data;
	while((int)offset - (int)starting < animation_data->header->size )
	{
		TileAnimation anim;

		anim.base = *reinterpret_cast<short*>(offset);
		offset += sizeof(short);

		anim.frame_rate = *reinterpret_cast<char*>(offset);
		offset += sizeof(char);

		anim.repeat = *reinterpret_cast<unsigned char*>(offset);
		offset += sizeof(unsigned char);

		anim.anim_length = *reinterpret_cast<char*>(offset);
		offset += sizeof(char);

		// unused char in file structure
		offset += sizeof(char);

		anim.tiles = reinterpret_cast<short*>(offset);
		offset += anim.anim_length * sizeof(short);

		std::vector<int> animationTiles;

		for(int i=0; i<anim.anim_length;i++)
		{
			animationTiles.push_back(anim.tiles[i]);
		}

		animatedGeom[anim.base].curTile = 0;
		animatedGeom[anim.base].tick = 0;
		animatedGeom[anim.base].anim = anim;
		animatedGeom[anim.base].animationTiles = animationTiles;

		animatedGeom[anim.base+1000].curTile = 0;
		animatedGeom[anim.base+1000].tick = 0;
		animatedGeom[anim.base+1000].anim = anim;
		animatedGeom[anim.base+1000].animationTiles = animationTiles;

		tileAnimations.push_back(anim);

		std::cout << anim.base << " " << (int)anim.frame_rate << " " << (int)anim.repeat << " " << (int)anim.anim_length << " " << anim.tiles[1] << " " << animationTiles.size() << std::endl;
	}

	// Read dmap data
	CompressedMap c_map;
	offset = dmap_data->data;
	c_map.base = reinterpret_cast<int*>(offset);
	offset += 256 * 256 * sizeof(int);

	c_map.column_words = *reinterpret_cast<int*>(offset);
	offset += sizeof(int);

	c_map.columns = reinterpret_cast<int*>(offset);
	offset += c_map.column_words * sizeof(int);

	c_map.num_blocks = *reinterpret_cast<int*>(offset);
	offset += sizeof(int);

	c_map.blocks = reinterpret_cast<BlockInfo*>(offset);
	offset += c_map.num_blocks * sizeof(BlockInfo);

	for(int x=0;x<255;x++) for(int y=0;y<255;y++) 
	{
		int base = c_map.base[y*256+x];
		

		ColInfo* column = reinterpret_cast<ColInfo*>(c_map.columns + base);

		int i = 0;

		for(i=0;i<(column->height-column->offset);i++){
			this->addBlock(c_map.blocks[column->blockd[i]], Vector3(x, -y, i+column->offset));
		}
	}
	delete reader;

	GLenum FBOstatus;
	
	glGenTextures(1, &depthTextureId);
	glBindTexture(GL_TEXTURE_2D, depthTextureId);
	
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP );
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP );
	
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_R_TO_TEXTURE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);
	glTexParameteri(GL_TEXTURE_2D, GL_DEPTH_TEXTURE_MODE, GL_INTENSITY); 
	
	glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, shadowMapWidth, shadowMapHeight, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, 0);
	glBindTexture(GL_TEXTURE_2D, 0);
	
	glGenFramebuffers(1, &fboId);
	glBindFramebuffer(GL_FRAMEBUFFER, fboId);
	
	glDrawBuffer(GL_NONE);
	glReadBuffer(GL_NONE);
	
	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depthTextureId, 0);
	
	FBOstatus = glCheckFramebufferStatus(GL_FRAMEBUFFER);
	if(FBOstatus != GL_FRAMEBUFFER_COMPLETE)
	{
		std::cout << "FBO error: " << FBOstatus << std::endl;
	}
	glBindFramebufferEXT(GL_FRAMEBUFFER, 0);
}
Exemplo n.º 17
0
void processFn(struct fnargs* args) {
	switch (args->fn) {
	case glfnUNDEFINED:
		abort(); // bad glfn
		break;
	case glfnActiveTexture:
		glActiveTexture((GLenum)args->a0);
		break;
	case glfnAttachShader:
		glAttachShader((GLint)args->a0, (GLint)args->a1);
		break;
	case glfnBindAttribLocation:
		glBindAttribLocation((GLint)args->a0, (GLint)args->a1, (GLchar*)args->a2);
		free((void*)args->a2);
		break;
	case glfnBindBuffer:
		glBindBuffer((GLenum)args->a0, (GLuint)args->a1);
		break;
	case glfnBindFramebuffer:
		glBindFramebuffer((GLenum)args->a0, (GLint)args->a1);
		break;
	case glfnBindRenderbuffer:
		glBindRenderbuffer((GLenum)args->a0, (GLint)args->a1);
		break;
	case glfnBindTexture:
		glBindTexture((GLenum)args->a0, (GLint)args->a1);
		break;
	case glfnBlendColor:
		glBlendColor(*(GLfloat*)&args->a0, *(GLfloat*)&args->a1, *(GLfloat*)&args->a2, *(GLfloat*)&args->a3);
		break;
	case glfnBlendEquation:
		glBlendEquation((GLenum)args->a0);
		break;
	case glfnBlendEquationSeparate:
		glBlendEquationSeparate((GLenum)args->a0, (GLenum)args->a1);
		break;
	case glfnBlendFunc:
		glBlendFunc((GLenum)args->a0, (GLenum)args->a1);
		break;
	case glfnBlendFuncSeparate:
		glBlendFuncSeparate((GLenum)args->a0, (GLenum)args->a1, (GLenum)args->a2, (GLenum)args->a3);
		break;
	case glfnBufferData:
		glBufferData((GLenum)args->a0, (GLsizeiptr)args->a1, (GLvoid*)args->a2, (GLenum)args->a3);
		break;
	case glfnBufferSubData:
		glBufferSubData((GLenum)args->a0, (GLint)args->a1, (GLsizeiptr)args->a2, (GLvoid*)args->a3);
		break;
	case glfnCheckFramebufferStatus:
		ret = glCheckFramebufferStatus((GLenum)args->a0);
		break;
	case glfnClear:
		glClear((GLenum)args->a0);
		break;
	case glfnClearColor:
		glClearColor(*(GLfloat*)&args->a0, *(GLfloat*)&args->a1, *(GLfloat*)&args->a2, *(GLfloat*)&args->a3);
		break;
	case glfnClearDepthf:
		glClearDepthf(*(GLfloat*)&args->a0);
		break;
	case glfnClearStencil:
		glClearStencil((GLint)args->a0);
		break;
	case glfnColorMask:
		glColorMask((GLboolean)args->a0, (GLboolean)args->a1, (GLboolean)args->a2, (GLboolean)args->a3);
		break;
	case glfnCompileShader:
		glCompileShader((GLint)args->a0);
		break;
	case glfnCompressedTexImage2D:
		glCompressedTexImage2D((GLenum)args->a0, (GLint)args->a1, (GLenum)args->a2, (GLint)args->a3, (GLint)args->a4, (GLint)args->a5, (GLsizeiptr)args->a6, (GLvoid*)args->a7);
		break;
	case glfnCompressedTexSubImage2D:
		glCompressedTexSubImage2D((GLenum)args->a0, (GLint)args->a1, (GLint)args->a2, (GLint)args->a3, (GLint)args->a4, (GLint)args->a5, (GLenum)args->a6, (GLsizeiptr)args->a7, (GLvoid*)args->a8);
		break;
	case glfnCopyTexImage2D:
		glCopyTexImage2D((GLenum)args->a0, (GLint)args->a1, (GLenum)args->a2, (GLint)args->a3, (GLint)args->a4, (GLint)args->a5, (GLint)args->a6, (GLint)args->a7);
		break;
	case glfnCopyTexSubImage2D:
		glCopyTexSubImage2D((GLenum)args->a0, (GLint)args->a1, (GLint)args->a2, (GLint)args->a3, (GLint)args->a4, (GLint)args->a5, (GLint)args->a6, (GLint)args->a7);
		break;
	case glfnCreateProgram:
		ret = glCreateProgram();
		break;
	case glfnCreateShader:
		ret = glCreateShader((GLenum)args->a0);
		break;
	case glfnCullFace:
		glCullFace((GLenum)args->a0);
		break;
	case glfnDeleteBuffer:
		glDeleteBuffers(1, (const GLuint*)(&args->a0));
		break;
	case glfnDeleteFramebuffer:
		glDeleteFramebuffers(1, (const GLuint*)(&args->a0));
		break;
	case glfnDeleteProgram:
		glDeleteProgram((GLint)args->a0);
		break;
	case glfnDeleteRenderbuffer:
		glDeleteRenderbuffers(1, (const GLuint*)(&args->a0));
		break;
	case glfnDeleteShader:
		glDeleteShader((GLint)args->a0);
		break;
	case glfnDeleteTexture:
		glDeleteTextures(1, (const GLuint*)(&args->a0));
		break;
	case glfnDepthFunc:
		glDepthFunc((GLenum)args->a0);
		break;
	case glfnDepthMask:
		glDepthMask((GLboolean)args->a0);
		break;
	case glfnDepthRangef:
		glDepthRangef(*(GLfloat*)&args->a0, *(GLfloat*)&args->a1);
		break;
	case glfnDetachShader:
		glDetachShader((GLint)args->a0, (GLint)args->a1);
		break;
	case glfnDisable:
		glDisable((GLenum)args->a0);
		break;
	case glfnDisableVertexAttribArray:
		glDisableVertexAttribArray((GLint)args->a0);
		break;
	case glfnDrawArrays:
		glDrawArrays((GLenum)args->a0, (GLint)args->a1, (GLint)args->a2);
		break;
	case glfnDrawElements:
		glDrawElements((GLenum)args->a0, (GLint)args->a1, (GLenum)args->a2, (void*)args->a3);
		break;
	case glfnEnable:
		glEnable((GLenum)args->a0);
		break;
	case glfnEnableVertexAttribArray:
		glEnableVertexAttribArray((GLint)args->a0);
		break;
	case glfnFinish:
		glFinish();
		break;
	case glfnFlush:
		glFlush();
		break;
	case glfnFramebufferRenderbuffer:
		glFramebufferRenderbuffer((GLenum)args->a0, (GLenum)args->a1, (GLenum)args->a2, (GLint)args->a3);
		break;
	case glfnFramebufferTexture2D:
		glFramebufferTexture2D((GLenum)args->a0, (GLenum)args->a1, (GLenum)args->a2, (GLint)args->a3, (GLint)args->a4);
		break;
	case glfnFrontFace:
		glFrontFace((GLenum)args->a0);
		break;
	case glfnGenBuffer:
		glGenBuffers(1, (GLuint*)&ret);
		break;
	case glfnGenFramebuffer:
		glGenFramebuffers(1, (GLuint*)&ret);
		break;
	case glfnGenRenderbuffer:
		glGenRenderbuffers(1, (GLuint*)&ret);
		break;
	case glfnGenTexture:
		glGenTextures(1, (GLuint*)&ret);
		break;
	case glfnGenerateMipmap:
		glGenerateMipmap((GLenum)args->a0);
		break;
	case glfnGetActiveAttrib:
		glGetActiveAttrib(
			(GLuint)args->a0,
			(GLuint)args->a1,
			(GLsizei)args->a2,
			NULL,
			(GLint*)args->a4,
			(GLenum*)args->a5,
			(GLchar*)args->a6);
		break;
	case glfnGetActiveUniform:
		glGetActiveUniform(
			(GLuint)args->a0,
			(GLuint)args->a1,
			(GLsizei)args->a2,
			NULL,
			(GLint*)args->a4,
			(GLenum*)args->a5,
			(GLchar*)args->a6);
		break;
	case glfnGetAttachedShaders:
		glGetAttachedShaders((GLuint)args->a0, (GLsizei)args->a1, (GLsizei*)args->a2, (GLuint*)args->a3);
		break;
	case glfnGetAttribLocation:
		ret = glGetAttribLocation((GLint)args->a0, (GLchar*)args->a1);
		free((void*)args->a1);
		break;
	case glfnGetBooleanv:
		glGetBooleanv((GLenum)args->a0, (GLboolean*)args->a1);
		break;
	case glfnGetBufferParameteri:
		glGetBufferParameteriv((GLenum)args->a0, (GLenum)args->a1, (GLint*)&ret);
		break;
	case glfnGetFloatv:
		glGetFloatv((GLenum)args->a0, (GLfloat*)args->a1);
		break;
	case glfnGetIntegerv:
		glGetIntegerv((GLenum)args->a0, (GLint*)args->a1);
		break;
	case glfnGetError:
		ret = glGetError();
		break;
	case glfnGetFramebufferAttachmentParameteriv:
		glGetFramebufferAttachmentParameteriv((GLenum)args->a0, (GLenum)args->a1, (GLenum)args->a2, (GLint*)&ret);
		break;
	case glfnGetProgramiv:
		glGetProgramiv((GLint)args->a0, (GLenum)args->a1, (GLint*)&ret);
		break;
	case glfnGetProgramInfoLog:
		glGetProgramInfoLog((GLuint)args->a0, (GLsizei)args->a1, (GLsizei*)args->a2, (GLchar*)args->a3);
		break;
	case glfnGetRenderbufferParameteriv:
		glGetRenderbufferParameteriv((GLenum)args->a0, (GLenum)args->a1, (GLint*)&ret);
		break;
	case glfnGetShaderiv:
		glGetShaderiv((GLint)args->a0, (GLenum)args->a1, (GLint*)&ret);
		break;
	case glfnGetShaderInfoLog:
		glGetShaderInfoLog((GLuint)args->a0, (GLsizei)args->a1, (GLsizei*)args->a2, (GLchar*)args->a3);
		break;
	case glfnGetShaderPrecisionFormat:
		glGetShaderPrecisionFormat((GLenum)args->a0, (GLenum)args->a1, (GLint*)args->a2, (GLint*)args->a3);
		break;
	case glfnGetShaderSource:
		glGetShaderSource((GLuint)args->a0, (GLsizei)args->a1, (GLsizei*)args->a2, (GLchar*)args->a3);
		break;
	case glfnGetString:
		ret = (uintptr_t)glGetString((GLenum)args->a0);
		break;
	case glfnGetTexParameterfv:
		glGetTexParameterfv((GLenum)args->a0, (GLenum)args->a1, (GLfloat*)args->a2);
		break;
	case glfnGetTexParameteriv:
		glGetTexParameteriv((GLenum)args->a0, (GLenum)args->a1, (GLint*)args->a2);
		break;
	case glfnGetUniformfv:
		glGetUniformfv((GLuint)args->a0, (GLint)args->a1, (GLfloat*)args->a2);
		break;
	case glfnGetUniformiv:
		glGetUniformiv((GLuint)args->a0, (GLint)args->a1, (GLint*)args->a2);
		break;
	case glfnGetUniformLocation:
		ret = glGetUniformLocation((GLint)args->a0, (GLchar*)args->a1);
		free((void*)args->a1);
		break;
	case glfnGetVertexAttribfv:
		glGetVertexAttribfv((GLuint)args->a0, (GLenum)args->a1, (GLfloat*)args->a2);
		break;
	case glfnGetVertexAttribiv:
		glGetVertexAttribiv((GLuint)args->a0, (GLenum)args->a1, (GLint*)args->a2);
		break;
	case glfnHint:
		glHint((GLenum)args->a0, (GLenum)args->a1);
		break;
	case glfnIsBuffer:
		ret = glIsBuffer((GLint)args->a0);
		break;
	case glfnIsEnabled:
		ret = glIsEnabled((GLenum)args->a0);
		break;
	case glfnIsFramebuffer:
		ret = glIsFramebuffer((GLint)args->a0);
		break;
	case glfnIsProgram:
		ret = glIsProgram((GLint)args->a0);
		break;
	case glfnIsRenderbuffer:
		ret = glIsRenderbuffer((GLint)args->a0);
		break;
	case glfnIsShader:
		ret = glIsShader((GLint)args->a0);
		break;
	case glfnIsTexture:
		ret = glIsTexture((GLint)args->a0);
		break;
	case glfnLineWidth:
		glLineWidth(*(GLfloat*)&args->a0);
		break;
	case glfnLinkProgram:
		glLinkProgram((GLint)args->a0);
		break;
	case glfnPixelStorei:
		glPixelStorei((GLenum)args->a0, (GLint)args->a1);
		break;
	case glfnPolygonOffset:
		glPolygonOffset(*(GLfloat*)&args->a0, *(GLfloat*)&args->a1);
		break;
	case glfnReadPixels:
		glReadPixels((GLint)args->a0, (GLint)args->a1, (GLsizei)args->a2, (GLsizei)args->a3, (GLenum)args->a4, (GLenum)args->a5, (void*)args->a6);
		break;
	case glfnReleaseShaderCompiler:
		glReleaseShaderCompiler();
		break;
	case glfnRenderbufferStorage:
		glRenderbufferStorage((GLenum)args->a0, (GLenum)args->a1, (GLint)args->a2, (GLint)args->a3);
		break;
	case glfnSampleCoverage:
		glSampleCoverage(*(GLfloat*)&args->a0, (GLboolean)args->a1);
		break;
	case glfnScissor:
		glScissor((GLint)args->a0, (GLint)args->a1, (GLint)args->a2, (GLint)args->a3);
		break;
	case glfnShaderSource:
#if defined(os_ios) || defined(os_osx)
		glShaderSource((GLuint)args->a0, (GLsizei)args->a1, (const GLchar *const *)args->a2, NULL);
#else
		glShaderSource((GLuint)args->a0, (GLsizei)args->a1, (const GLchar **)args->a2, NULL);
#endif
		free(*(void**)args->a2);
		free((void*)args->a2);
		break;
	case glfnStencilFunc:
		glStencilFunc((GLenum)args->a0, (GLint)args->a1, (GLuint)args->a2);
		break;
	case glfnStencilFuncSeparate:
		glStencilFuncSeparate((GLenum)args->a0, (GLenum)args->a1, (GLint)args->a2, (GLuint)args->a3);
		break;
	case glfnStencilMask:
		glStencilMask((GLuint)args->a0);
		break;
	case glfnStencilMaskSeparate:
		glStencilMaskSeparate((GLenum)args->a0, (GLuint)args->a1);
		break;
	case glfnStencilOp:
		glStencilOp((GLenum)args->a0, (GLenum)args->a1, (GLenum)args->a2);
		break;
	case glfnStencilOpSeparate:
		glStencilOpSeparate((GLenum)args->a0, (GLenum)args->a1, (GLenum)args->a2, (GLenum)args->a3);
		break;
	case glfnTexImage2D:
		glTexImage2D(
			(GLenum)args->a0,
			(GLint)args->a1,
			(GLint)args->a2,
			(GLsizei)args->a3,
			(GLsizei)args->a4,
			0, // border
			(GLenum)args->a5,
			(GLenum)args->a6,
			(const GLvoid*)args->a7);
		break;
	case glfnTexSubImage2D:
		glTexSubImage2D(
			(GLenum)args->a0,
			(GLint)args->a1,
			(GLint)args->a2,
			(GLint)args->a3,
			(GLsizei)args->a4,
			(GLsizei)args->a5,
			(GLenum)args->a6,
			(GLenum)args->a7,
			(const GLvoid*)args->a8);
		break;
	case glfnTexParameterf:
		glTexParameterf((GLenum)args->a0, (GLenum)args->a1, *(GLfloat*)&args->a2);
		break;
	case glfnTexParameterfv:
		glTexParameterfv((GLenum)args->a0, (GLenum)args->a1, (GLfloat*)args->a2);
		break;
	case glfnTexParameteri:
		glTexParameteri((GLenum)args->a0, (GLenum)args->a1, (GLint)args->a2);
		break;
	case glfnTexParameteriv:
		glTexParameteriv((GLenum)args->a0, (GLenum)args->a1, (GLint*)args->a2);
		break;
	case glfnUniform1f:
		glUniform1f((GLint)args->a0, *(GLfloat*)&args->a1);
		break;
	case glfnUniform1fv:
		glUniform1fv((GLint)args->a0, (GLsizeiptr)args->a1, (GLvoid*)args->a2);
		break;
	case glfnUniform1i:
		glUniform1i((GLint)args->a0, (GLint)args->a1);
		break;
	case glfnUniform1iv:
		glUniform1iv((GLint)args->a0, (GLsizeiptr)args->a1, (GLvoid*)args->a2);
		break;
	case glfnUniform2f:
		glUniform2f((GLint)args->a0, *(GLfloat*)&args->a1, *(GLfloat*)&args->a2);
		break;
	case glfnUniform2fv:
		glUniform2fv((GLint)args->a0, (GLsizeiptr)args->a1, (GLvoid*)args->a2);
		break;
	case glfnUniform2i:
		glUniform2i((GLint)args->a0, (GLint)args->a1, (GLint)args->a2);
		break;
	case glfnUniform2iv:
		glUniform2iv((GLint)args->a0, (GLsizeiptr)args->a1, (GLvoid*)args->a2);
		break;
	case glfnUniform3f:
		glUniform3f((GLint)args->a0, *(GLfloat*)&args->a1, *(GLfloat*)&args->a2, *(GLfloat*)&args->a3);
		break;
	case glfnUniform3fv:
		glUniform3fv((GLint)args->a0, (GLsizeiptr)args->a1, (GLvoid*)args->a2);
		break;
	case glfnUniform3i:
		glUniform3i((GLint)args->a0, (GLint)args->a1, (GLint)args->a2, (GLint)args->a3);
		break;
	case glfnUniform3iv:
		glUniform3iv((GLint)args->a0, (GLsizeiptr)args->a1, (GLvoid*)args->a2);
		break;
	case glfnUniform4f:
		glUniform4f((GLint)args->a0, *(GLfloat*)&args->a1, *(GLfloat*)&args->a2, *(GLfloat*)&args->a3, *(GLfloat*)&args->a4);
		break;
	case glfnUniform4fv:
		glUniform4fv((GLint)args->a0, (GLsizeiptr)args->a1, (GLvoid*)args->a2);
		break;
	case glfnUniform4i:
		glUniform4i((GLint)args->a0, (GLint)args->a1, (GLint)args->a2, (GLint)args->a3, (GLint)args->a4);
		break;
	case glfnUniform4iv:
		glUniform4iv((GLint)args->a0, (GLsizeiptr)args->a1, (GLvoid*)args->a2);
		break;
	case glfnUniformMatrix2fv:
		glUniformMatrix2fv((GLint)args->a0, (GLsizeiptr)args->a1, 0, (GLvoid*)args->a2);
		break;
	case glfnUniformMatrix3fv:
		glUniformMatrix3fv((GLint)args->a0, (GLsizeiptr)args->a1, 0, (GLvoid*)args->a2);
		break;
	case glfnUniformMatrix4fv:
		glUniformMatrix4fv((GLint)args->a0, (GLsizeiptr)args->a1, 0, (GLvoid*)args->a2);
		break;
	case glfnUseProgram:
		glUseProgram((GLint)args->a0);
		break;
	case glfnValidateProgram:
		glValidateProgram((GLint)args->a0);
		break;
	case glfnVertexAttrib1f:
		glVertexAttrib1f((GLint)args->a0, *(GLfloat*)&args->a1);
		break;
	case glfnVertexAttrib1fv:
		glVertexAttrib1fv((GLint)args->a0, (GLfloat*)args->a1);
		break;
	case glfnVertexAttrib2f:
		glVertexAttrib2f((GLint)args->a0, *(GLfloat*)&args->a1, *(GLfloat*)&args->a2);
		break;
	case glfnVertexAttrib2fv:
		glVertexAttrib2fv((GLint)args->a0, (GLfloat*)args->a1);
		break;
	case glfnVertexAttrib3f:
		glVertexAttrib3f((GLint)args->a0, *(GLfloat*)&args->a1, *(GLfloat*)&args->a2, *(GLfloat*)&args->a3);
		break;
	case glfnVertexAttrib3fv:
		glVertexAttrib3fv((GLint)args->a0, (GLfloat*)args->a1);
		break;
	case glfnVertexAttrib4f:
		glVertexAttrib4f((GLint)args->a0, *(GLfloat*)&args->a1, *(GLfloat*)&args->a2, *(GLfloat*)&args->a3, *(GLfloat*)&args->a4);
		break;
	case glfnVertexAttrib4fv:
		glVertexAttrib4fv((GLint)args->a0, (GLfloat*)args->a1);
		break;
	case glfnVertexAttribPointer:
		glVertexAttribPointer((GLuint)args->a0, (GLint)args->a1, (GLenum)args->a2, (GLboolean)args->a3, (GLsizei)args->a4, (const GLvoid*)args->a5);
		break;
	case glfnViewport:
		glViewport((GLint)args->a0, (GLint)args->a1, (GLint)args->a2, (GLint)args->a3);
		break;
	}
}
Exemplo n.º 18
0
renderToTexture::renderToTexture(int width, int height, bool depthTest, GLenum format) : width(width), height(height), depthTest(depthTest), format(format) {
	this->gen();

	setupThrow(LOG, glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE, "Setup done");
}
Exemplo n.º 19
0
GC3Denum GraphicsContext3D::checkFramebufferStatus(GC3Denum target)
{
    makeContextCurrent();
    return glCheckFramebufferStatus(target);
}
Exemplo n.º 20
0
bool OlaGLRenderTarget::initialize( int w ,int h )
{
	release();

	mWidth = w;
	mHeight = h;

//color buffer
	unsigned int color_rb = 0;
	glGenTextures(1, &color_rb);
	lgGLError("color buffer gen failed in rt \n");

    glBindTexture(GL_TEXTURE_2D, color_rb);
	lgGLError("color buffer bind failed in rt \n");
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, mWidth, mHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE , 0); //rgba  GL_UNSIGNED_SHORT_5_6_5 GL_UNSIGNED_BYTE
	lgGLError("color buffer create failed in rt \n");

	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	
	glBindTexture(GL_TEXTURE_2D, 0);

//depth buffer
	unsigned int depth_rb = 0;
	glGenTextures(1, &depth_rb);
	lgGLError("depth buffer gen failed in rt \n");

    glBindTexture(GL_TEXTURE_2D, depth_rb);
	lgGLError("depth buffer bind failed in rt \n");
    glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, mWidth, mHeight, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT , 0); //rgba  GL_UNSIGNED_SHORT_5_6_5 GL_UNSIGNED_BYTE
	lgGLError("depth buffer create failed in rt \n");

	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	
	glBindTexture(GL_TEXTURE_2D, 0);

//stencil buffer
	//unsigned int stencel_buffer = 0;
	//glGenRenderbuffers(1,&stencel_buffer);
	//glBindRenderbuffer(GL_RENDERBUFFER,stencel_buffer);
	//glRenderbufferStorage(GL_RENDERBUFFER,GL_STENCIL_INDEX8,mWidth,mHeight);
	//lgGLError("stencil buffer create failed in rt \n");
	//glBindRenderbuffer(GL_RENDERBUFFER,0);


	unsigned int fbo = 0;
	glGenFramebuffers(1,&fbo);
	glBindFramebuffer(GL_FRAMEBUFFER,fbo);
	lgGLError("frame buffer gen failed in rt \n");
	mHandles[OlaRTParam::FRAME_BUFFER] = fbo;

	mHandles[OlaRTParam::COLOR_BUFFER] = color_rb;
	glFramebufferTexture2D(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT0,GL_TEXTURE_2D, color_rb,0);
	lgGLError("color buffer attach failed in rt \n");

	mHandles[OlaRTParam::DEPTH_BUFFER] = depth_rb;
	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,GL_TEXTURE_2D, depth_rb, 0);
	lgGLError("depth buffer attach failed in rt \n");

	//mHandles[OlaRTParam::STENCIL_BUFFER] = stencel_buffer;
	//glFramebufferRenderbuffer(GL_FRAMEBUFFER,GL_STENCIL_ATTACHMENT,GL_RENDERBUFFER,stencel_buffer); 
	//lgGLError("stencil buffer attach failed in rt \n");

	GLenum hr = glCheckFramebufferStatus(GL_FRAMEBUFFER);
	switch (hr)
	{
	case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
		lg("GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT");
		break;
	case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS:
		lg("GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS");
		break;
	case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
		lg("GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT");
		break;
	case GL_FRAMEBUFFER_UNSUPPORTED:
		lg("GL_FRAMEBUFFER_UNSUPPORTED");
		break;
	case GL_FRAMEBUFFER_COMPLETE:
		break;
	}

	glBindFramebuffer(GL_FRAMEBUFFER,0);
    
	return true;
}
Exemplo n.º 21
0
DepthBuffer::DepthBuffer(unsigned int width, unsigned height) : width(width), 
                                                                height(height) {
  // Create FBO
  // --------------------------------------------------------------------------
  glGenFramebuffers(1, &(this->p_fbo));
  glBindFramebuffer(GL_DRAW_FRAMEBUFFER, this->p_fbo);

  // Create colour output texture buffer
  // --------------------------------------------------------------------------
  glGenTextures(1, &(this->p_colour_texture));

  glBindTexture(GL_TEXTURE_2D, this->p_colour_texture);
  glTexImage2D(GL_TEXTURE_2D,
               0,
               GL_RGB32F,
               this->width, this->height,
               0,
               GL_RGB,
               GL_UNSIGNED_SHORT_5_6_5,
               NULL
               );
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

  // Attach texture the framebuffer object
  glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER,     // target
                         GL_COLOR_ATTACHMENT0,    // attachment
                         GL_TEXTURE_2D,           // textarget
                         this->p_colour_texture,  // texture
                         0                        // level (mipmap level)
                         );

  // Create depth texture buffer
  // --------------------------------------------------------------------------
  glGenTextures(1, &(this->p_depth_texture));

  glBindTexture(GL_TEXTURE_2D, this->p_depth_texture);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_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_DEPTH_COMPONENT32F,
               this->width, this->height,
               0,
               GL_DEPTH_COMPONENT,
               GL_FLOAT,
               NULL
               );
  glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER,
                         GL_DEPTH_ATTACHMENT,
                         GL_TEXTURE_2D,
                         this->p_depth_texture,
                         0
                         );

  //glDrawBuffer(GL_NONE);
  GLenum draw_buffers[] = { GL_COLOR_ATTACHMENT0 };
  glDrawBuffers(1, draw_buffers);

  GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  if (status != GL_FRAMEBUFFER_COMPLETE) {
    throw std::runtime_error(std::string("FB error, status: 0x%x\n", status));
  }

  glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
}
Exemplo n.º 22
0
/*---------------------------------------------------------------------------
   Setup function that a intialises assets, matrices and other OpenGL
   related structure for rendering. NOTE: This must be called within a 
   valid OpenGL context.
  ---------------------------------------------------------------------------*/
void Filter::Setup(Buffers &Buffer)
   {
   Destroy();

   if (!GLEW_ARB_framebuffer_object)
      {throw dexception("Current OpenGL context does not support frame buffer objects.");}

   vector2u Res;
   
   switch (Select)
      {
      case Filter::SelectVideo : Res = Buffer.GetVideoResolution(); break;
      case Filter::SelectDepth : Res = Buffer.GetDepthResolution(); break;
      default : throw dexception("Invalid Select enumeration.");;
      }

   if (Res.X < 1 || Res.Y < 1) {return;}
   
   //Create a new frame buffer object
   glGenFramebuffers(1, &FBOID);
   glBindFramebuffer(GL_FRAMEBUFFER, FBOID);

   //Create a new depth buffer object, then associate a 
   // storage space for it, and attach it to the FBO
   glGenRenderbuffers(1, &DBOID);
   glBindRenderbuffer(GL_RENDERBUFFER, DBOID);
   glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, Res.X, Res.Y);
   glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, DBOID);

   //Create a colour buffer in form of a texture and attach it to the FBO
   glGenTextures(1, &CBOID);
   glBindTexture(GL_TEXTURE_2D, CBOID);
   glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, Res.X, Res.Y, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
   glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, CBOID, 0);

   //FBO texture scaling
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_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);
   glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE);

   //Setup view port size
   ViewPort.Set4(0, 0, Res.X, Res.Y);

   //Compute frustum aspect ratio from viewport size
   Ratio.Set((float)ViewPort.C2, (float)ViewPort.C3);
   Ratio /= (float)Math::Min(ViewPort.C2, ViewPort.C3);

   //Default projection matrix
   MP = MP.Identity();
   MP = MP.Ortho(-Ratio.X, Ratio.X, -Ratio.Y, Ratio.Y, Near, Far);

   //Default model view matrix
   MV = MV.Identity();
   MV = MV.Scale(Ratio.X, Ratio.Y, 1.0f);

   //Default texture matrix
   MT = MT.Identity();
   //MT = MT.Scale(1.0f, -1.0f, 1.0f);
   //MT = MT.Translate(0.0f, -1.0f, 0.0f);

   MC = MC.Identity();

   //Error checking   
   GLenum Error = glCheckFramebufferStatus(GL_FRAMEBUFFER);
   if (Error != GL_FRAMEBUFFER_COMPLETE) {throw dexception("Failed to setup frame buffer object: %s.", Debug::StatusFBO(Error));}

   Error = glGetError();
   if (Error != GL_NO_ERROR) {throw dexception("OpenGL generated an error: %s", Debug::ErrorGL(Error));}
   }
Exemplo n.º 23
0
void CGLFramebuffer::Create()
{
    if (m_fbo != 0) return;

    m_width = m_params.width;
    m_height = m_params.height;
    m_depth = m_params.depth;
    m_samples = m_params.samples;

    glGenFramebuffers(1, &m_fbo);
    glBindFramebuffer(GL_FRAMEBUFFER, m_fbo);

    // create color texture
    if (m_params.colorTexture)
    {
        GLint previous;
        glGetIntegerv(GL_TEXTURE_BINDING_2D, &previous);

        glGenTextures(1, &m_colorTexture);
        glBindTexture(GL_TEXTURE_2D, m_colorTexture);

        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, m_params.width, m_params.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

        glBindTexture(GL_TEXTURE_2D, previous);

        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_colorTexture, 0);
    }
    // create color renderbuffer
    else
    {
        glGenRenderbuffers(1, &m_colorRenderbuffer);
        glBindRenderbuffer(GL_RENDERBUFFER, m_colorRenderbuffer);

        if (m_params.samples > 1)
            glRenderbufferStorageMultisample(GL_RENDERBUFFER, m_params.samples, GL_RGBA8, m_params.width, m_params.height);
        else
            glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA8, m_params.width, m_params.height);

        glBindRenderbuffer(GL_RENDERBUFFER, 0);

        glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, m_colorRenderbuffer);
    }

    GLuint depthFormat = 0;

    switch (m_params.depth)
    {
    case 16: depthFormat = GL_DEPTH_COMPONENT16; break;
    case 24: depthFormat = GL_DEPTH_COMPONENT24; break;
    case 32: depthFormat = GL_DEPTH_COMPONENT32; break;
    default: depthFormat = GL_DEPTH_COMPONENT16; break;
    }

    // create depth texture
    if (m_params.depthTexture)
    {
        GLint previous;
        glGetIntegerv(GL_TEXTURE_BINDING_2D, &previous);

        glGenTextures(1, &m_depthTexture);
        glBindTexture(GL_TEXTURE_2D, m_depthTexture);

        glTexImage2D(GL_TEXTURE_2D, 0, depthFormat, m_params.width, m_params.height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, nullptr);

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);

        float color[] = { 1.0f, 1.0f, 1.0f, 1.0f };

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
        glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, color);

        glBindTexture(GL_TEXTURE_2D, previous);

        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, m_depthTexture, 0);
    }
    // create depth renderbuffer
    else
    {
        glGenRenderbuffers(1, &m_depthRenderbuffer);
        glBindRenderbuffer(GL_RENDERBUFFER, m_depthRenderbuffer);

        if (m_params.samples > 1)
            glRenderbufferStorageMultisample(GL_RENDERBUFFER, m_params.samples, depthFormat, m_params.width, m_params.height);
        else
            glRenderbufferStorage(GL_RENDERBUFFER, depthFormat, m_params.width, m_params.height);

        glBindRenderbuffer(GL_RENDERBUFFER, 0);

        glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, m_depthRenderbuffer);
    }

    GLuint result = glCheckFramebufferStatus(GL_FRAMEBUFFER);
    if (result != GL_FRAMEBUFFER_COMPLETE)
    {
        GetLogger()->Error("Framebuffer incomplete\n");
        assert(false);
    }

    glBindFramebuffer(GL_FRAMEBUFFER, m_currentFBO);
}
Exemplo n.º 24
0
	void opengl_window::render()
	{
		if (iRendering || processing_event())
			return;

		uint64_t now = app::instance().program_elapsed_ms();
		if (iFrameRate != boost::none && now - iLastFrameTime < 1000 / *iFrameRate)
			return;

		if (!iEventHandler.native_window_ready_to_render())
			return;

		rendering_check.trigger();

		if (iInvalidatedRects.empty())
			return;

		++iFrameCounter;

		iRendering = true;
		iLastFrameTime = now;

		rendering.trigger();

		rect invalidatedRect = *iInvalidatedRects.begin();
		for (const auto& ir : iInvalidatedRects)
		{
			invalidatedRect = invalidatedRect.combine(ir);
		}
		iInvalidatedRects.clear();
		invalidatedRect.cx = std::min(invalidatedRect.cx, surface_size().cx - invalidatedRect.x);
		invalidatedRect.cy = std::min(invalidatedRect.cy, surface_size().cy - invalidatedRect.y);

		static bool initialized = false;
		if (!initialized)
		{
			rendering_engine().initialize();
			initialized = true;
		}

		activate_context();

		glCheck(glViewport(0, 0, static_cast<GLsizei>(extents().cx), static_cast<GLsizei>(extents().cy)));
		glCheck(glMatrixMode(GL_PROJECTION));
		glCheck(glLoadIdentity());
		glCheck(glScalef(1.0, 1.0, 1.0));
		glCheck(glMatrixMode(GL_MODELVIEW));
		glCheck(glLoadIdentity());
		const auto& logicalCoordinates = logical_coordinates();
		glCheck(glOrtho(logicalCoordinates[0], logicalCoordinates[2], logicalCoordinates[1], logicalCoordinates[3], -1.0, 1.0));
		glCheck(glEnableClientState(GL_VERTEX_ARRAY));
		glCheck(glEnableClientState(GL_COLOR_ARRAY));
		glCheck(glEnableClientState(GL_TEXTURE_COORD_ARRAY));
		glCheck(glEnable(GL_TEXTURE_2D));
		glCheck(glEnable(GL_MULTISAMPLE));
		glCheck(glEnable(GL_BLEND));
		if (iFrameBufferSize.cx < static_cast<double>(extents().cx) || iFrameBufferSize.cy < static_cast<double>(extents().cy))
		{
			if (iFrameBufferSize != size{})
			{
				glCheck(glDeleteRenderbuffers(1, &iDepthStencilBuffer));
				glCheck(glDeleteTextures(1, &iFrameBufferTexture));
				glCheck(glDeleteFramebuffers(1, &iFrameBuffer));
			}
			iFrameBufferSize = size(
				iFrameBufferSize.cx < extents().cx ? extents().cx * 1.5f : iFrameBufferSize.cx,
				iFrameBufferSize.cy < extents().cy ? extents().cy * 1.5f : iFrameBufferSize.cy);
			glCheck(glGenFramebuffers(1, &iFrameBuffer));
			glCheck(glBindFramebuffer(GL_FRAMEBUFFER, iFrameBuffer));
			glCheck(glGenTextures(1, &iFrameBufferTexture));
			glCheck(glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, iFrameBufferTexture));
			glCheck(glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, 4, GL_RGBA8, static_cast<GLsizei>(iFrameBufferSize.cx), static_cast<GLsizei>(iFrameBufferSize.cy), true));
			glCheck(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D_MULTISAMPLE, iFrameBufferTexture, 0));
			glCheck(glGenRenderbuffers(1, &iDepthStencilBuffer));
			glCheck(glBindRenderbuffer(GL_RENDERBUFFER, iDepthStencilBuffer));
			glCheck(glRenderbufferStorageMultisample(GL_RENDERBUFFER, 4, GL_DEPTH24_STENCIL8, static_cast<GLsizei>(iFrameBufferSize.cx), static_cast<GLsizei>(iFrameBufferSize.cy)));
			glCheck(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, iDepthStencilBuffer));
			glCheck(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, iDepthStencilBuffer));
		}
		else
		{
			glCheck(glBindFramebuffer(GL_FRAMEBUFFER, iFrameBuffer));
			glCheck(glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, iFrameBufferTexture));
			glCheck(glBindRenderbuffer(GL_RENDERBUFFER, iDepthStencilBuffer));
		}
		GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
		if (status != GL_NO_ERROR && status != GL_FRAMEBUFFER_COMPLETE)
			throw failed_to_create_framebuffer(status);
		glCheck(glBindFramebuffer(GL_FRAMEBUFFER, iFrameBuffer));
		GLenum drawBuffers[] = { GL_COLOR_ATTACHMENT0 };
		glCheck(glDrawBuffers(sizeof(drawBuffers) / sizeof(drawBuffers[0]), drawBuffers));

		glCheck(iEventHandler.native_window_render(invalidatedRect));

		glCheck(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0));
		glCheck(glBindFramebuffer(GL_READ_FRAMEBUFFER, iFrameBuffer));
		glCheck(glBlitFramebuffer(0, 0, static_cast<GLint>(extents().cx), static_cast<GLint>(extents().cy), 0, 0, static_cast<GLint>(extents().cx), static_cast<GLint>(extents().cy), GL_COLOR_BUFFER_BIT, GL_NEAREST));

		display();
		deactivate_context();

		iRendering = false;

		rendering_finished.trigger();
	}
Exemplo n.º 25
0
		EGBufferStatus::Value CheckFramebufferStatus(const EGBuffer::Value Target)
		{
			const EGBufferStatus::Value Status = static_cast<EGBufferStatus::Value>(glCheckFramebufferStatus(Target));
			return Status;
		}
Exemplo n.º 26
0
void Framebuffer::prepare(RenderState& rs, GLuint unit) {

  m_colorTexture.prepare(rs, unit);

  // Generate framebuffer handle.
  CHECK_GL(glGenFramebuffers(1, &m_framebufferHandle));

  if (m_options.hasDepth) {
    // Generate depth buffer handle.
    CHECK_GL(glGenRenderbuffers(1, &m_depthbufferHandle));
  }

  if (m_options.hasStencil) {
    // Generate stencil buffer handle.
    CHECK_GL(glGenRenderbuffers(1, &m_stencilbufferHandle));
  }

  // Bind color texture.
  m_colorTexture.bind(rs, unit);

  if (m_options.hasDepth) {
    // Create depth buffer storage.
    CHECK_GL(glBindRenderbuffer(GL_RENDERBUFFER, m_depthbufferHandle));
    CHECK_GL(glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, m_width, m_height));
  }

  if (m_options.hasStencil) {
    // Create stencil buffer storage.
    CHECK_GL(glBindRenderbuffer(GL_RENDERBUFFER, m_stencilbufferHandle));
    CHECK_GL(glRenderbufferStorage(GL_RENDERBUFFER, GL_STENCIL_INDEX8, m_width, m_height));
  }

  // Bind the framebuffer.
  CHECK_GL(glBindFramebuffer(GL_FRAMEBUFFER, m_framebufferHandle));

  // Attach the color buffer.
  CHECK_GL(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_colorTexture.glHandle(), 0));

  if (m_options.hasDepth) {
    // Attach the depth buffer.
    CHECK_GL(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, m_depthbufferHandle));
  }

  if (m_options.hasStencil) {
    // Attach the stencil buffer.
    CHECK_GL(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, m_stencilbufferHandle));
  }

  // Unbind renderbuffer object.
  CHECK_GL(glBindRenderbuffer(GL_RENDERBUFFER, 0));

  // Check framebuffer status.
  GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  CHECK_GL();

  // Bind the default framebuffer object.
  CHECK_GL(glBindFramebuffer(GL_FRAMEBUFFER, 0));

  // Check status and dispose on failure.
  if (status != GL_FRAMEBUFFER_COMPLETE) {

    dispose(rs);

    switch (status) {
    case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
      Log::e("Error creating framebuffer: GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT");
      break;
    case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
      Log::e("Error creating framebuffer: GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT");
      break;
    case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS:
      Log::e("Error creating framebuffer: GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS");
      break;
    case GL_FRAMEBUFFER_UNSUPPORTED:
      Log::e("Error creating framebuffer: GL_FRAMEBUFFER_UNSUPPORTED");
      break;
    default:
      Log::e("Error creating framebuffer: Unrecognized error.");
      break;
    }
  }
}
Exemplo n.º 27
0
bool CMaterialGlow::Init(SMaterialData* Data)
{
    if (Data == nullptr)
        return false;
    
//    static float_t quad[30] =
//    {
//        -1.0f, -1.0f, 0.0f,   0.0f, 0.0f,
//        1.0f, -1.0f, 0.0f,   1.0f, 0.0f,
//        1.0f, 1.0f, 0.0f,   1.0f, 1.0f,
//        -1.0f, -1.0f, 0.0f,   0.0f, 0.0f,
//        1.0f, 1.0f, 0.0f,   1.0f, 1.0f,
//        -1.0f, 1.0f, 0.0f,   0.0f, 1.0f
//    };
    
    GLint viewport[4];
    
    glGetIntegerv(GL_VIEWPORT, viewport);
    
    m_gTextureWidth = viewport[2];
    m_gTextureHeight = viewport[3];
//    
//    glGenTextures(1, &m_gTexture);
//    
//    glBindTexture(GL_TEXTURE_2D, m_gTexture);
//    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);
//    
//    if (!loadBmpImage(data->TextureFileName.c_str()))
//        return false;

    
    
    glGenFramebuffers(1, &m_gFB);
    glGenRenderbuffers(1, &m_gRB);
    glGenTextures(2, m_gTexture);

    glBindTexture(GL_TEXTURE_2D, m_gTexture[0]);
    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_RGBA, m_gTextureWidth, m_gTextureHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);

    glBindTexture(GL_TEXTURE_2D, m_gTexture[1]);
    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_RGBA, m_gTextureWidth, m_gTextureHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
    glBindTexture(GL_TEXTURE_2D, 0);
    
    glBindRenderbuffer(GL_RENDERBUFFER, m_gRB);
    glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA8_OES, m_gTextureWidth, m_gTextureHeight);
    glBindRenderbuffer(GL_RENDERBUFFER, 0);
    
    glBindFramebuffer(GL_FRAMEBUFFER, m_gFB);
    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, m_gRB);
    
    if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
    {
        __LOG("Faild to create frame buffer");
        
        return false;
    }

    glBindFramebuffer(GL_FRAMEBUFFER, Globals::GetDefaultFramebuffer());
    
    glGenVertexArraysOES(1, &m_gVAO);
    glBindVertexArrayOES(m_gVAO);
    
    glGenBuffers(1, &m_gVBO);
    glBindBuffer(GL_ARRAY_BUFFER, m_gVBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(quad), quad, GL_STATIC_DRAW);
    glEnableVertexAttribArray(SAL_POSITION);
    glVertexAttribPointer(SAL_POSITION, 3, GL_FLOAT, GL_FALSE, sizeof(float_t) * 5, 0);
    glEnableVertexAttribArray(SAL_TEXTURE_COORD);
    glVertexAttribPointer(SAL_TEXTURE_COORD, 2, GL_FLOAT, GL_FALSE, sizeof(float_t) * 5, (char*)NULL + (sizeof(float_t) * 3));
    
    glBindVertexArrayOES(0);

    return true;
}
Exemplo n.º 28
0
bool CCRenderTexture::initWithWidthAndHeight(int w, int h, CCTexture2DPixelFormat eFormat, GLuint uDepthStencilFormat)
{
    CCAssert(eFormat != kCCTexture2DPixelFormat_A8, "only RGB and RGBA formats are valid for a render texture");

    bool bRet = false;
    void *data = NULL;
    do 
    {
        w = (int)(w * CC_CONTENT_SCALE_FACTOR());
        h = (int)(h * CC_CONTENT_SCALE_FACTOR());

        glGetIntegerv(GL_FRAMEBUFFER_BINDING, &m_nOldFBO);

        // textures must be power of two squared
        unsigned int powW = 0;
        unsigned int powH = 0;

        if (CCConfiguration::sharedConfiguration()->supportsNPOT())
        {
            powW = w;
            powH = h;
        }
        else
        {
            powW = ccNextPOT(w);
            powH = ccNextPOT(h);
        }

        data = malloc((int)(powW * powH * 4));
        CC_BREAK_IF(! data);

        memset(data, 0, (int)(powW * powH * 4));
        m_ePixelFormat = eFormat;

        m_pTexture = new CCTexture2D();
        if (m_pTexture)
        {
            m_pTexture->initWithData(data, (CCTexture2DPixelFormat)m_ePixelFormat, powW, powH, CCSizeMake((float)w, (float)h));
        }
        else
        {
            break;
        }
        GLint oldRBO;
        glGetIntegerv(GL_RENDERBUFFER_BINDING, &oldRBO);
        
        if (CCConfiguration::sharedConfiguration()->checkForGLExtension("GL_QCOM"))
        {
            m_pTextureCopy = new CCTexture2D();
            if (m_pTextureCopy)
            {
                m_pTextureCopy->initWithData(data, (CCTexture2DPixelFormat)m_ePixelFormat, powW, powH, CCSizeMake((float)w, (float)h));
            }
            else
            {
                break;
            }
        }

        // generate FBO
        glGenFramebuffers(1, &m_uFBO);
        glBindFramebuffer(GL_FRAMEBUFFER, m_uFBO);

        // associate texture with FBO
        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_pTexture->getName(), 0);

        if (uDepthStencilFormat != 0)
        {
            //create and attach depth buffer
            glGenRenderbuffers(1, &m_uDepthRenderBufffer);
            glBindRenderbuffer(GL_RENDERBUFFER, m_uDepthRenderBufffer);
            glRenderbufferStorage(GL_RENDERBUFFER, uDepthStencilFormat, (GLsizei)powW, (GLsizei)powH);
            glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, m_uDepthRenderBufffer);

            // if depth format is the one with stencil part, bind same render buffer as stencil attachment
            if (uDepthStencilFormat == GL_DEPTH24_STENCIL8)
            {
                glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, m_uDepthRenderBufffer);
            }
        }

        // check if it worked (probably worth doing :) )
        CCAssert(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE, "Could not attach texture to framebuffer");

        m_pTexture->setAliasTexParameters();

        // retained
        setSprite(CCSprite::createWithTexture(m_pTexture));

        m_pTexture->release();
        m_pSprite->setScaleY(-1);

        ccBlendFunc tBlendFunc = {GL_ONE, GL_ONE_MINUS_SRC_ALPHA };
        m_pSprite->setBlendFunc(tBlendFunc);

        glBindRenderbuffer(GL_RENDERBUFFER, oldRBO);
        glBindFramebuffer(GL_FRAMEBUFFER, m_nOldFBO);
        
        // Diabled by default.
        m_bAutoDraw = false;
        
        // add sprite for backward compatibility
        addChild(m_pSprite);
        
        bRet = true;
    } while (0);
    
    CC_SAFE_FREE(data);
    
    return bRet;
}
Exemplo n.º 29
0
/* initialise secondary framebuffer. this will just allow us to render our main
scene to a texture instead of directly to the screen. returns false if something
went wrong in the framebuffer creation */
bool init_fb () {
	glGenFramebuffers (1, &g_fb);
	/* create the texture that will be attached to the fb. should be the same
	dimensions as the viewport */
	glGenTextures (1, &g_fb_tex);
	glBindTexture (GL_TEXTURE_2D, g_fb_tex);
	glTexImage2D (
		GL_TEXTURE_2D,
		0,
		GL_RGBA,
		g_gl_width,
		g_gl_height,
		0,
		GL_RGBA,
		GL_UNSIGNED_BYTE,
		NULL
	);
	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_MIN_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	/* attach the texture to the framebuffer */
	glBindFramebuffer (GL_FRAMEBUFFER, g_fb);
	glFramebufferTexture2D (
		GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, g_fb_tex, 0
	);
	/* create a renderbuffer which allows depth-testing in the framebuffer */
	GLuint rb = 0;
	glGenRenderbuffers (1, &rb);
	glBindRenderbuffer (GL_RENDERBUFFER, rb);
	glRenderbufferStorage (
		GL_RENDERBUFFER, GL_DEPTH_COMPONENT, g_gl_width, g_gl_height
	);
	/* attach renderbuffer to framebuffer */
	glFramebufferRenderbuffer (
		GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rb
	);
	/* tell the framebuffer to expect a colour output attachment (our texture) */
	GLenum draw_bufs[] = { GL_COLOR_ATTACHMENT0 };
	glDrawBuffers (1, draw_bufs);
	
	/* validate the framebuffer - an 'incomplete' error tells us if an invalid
	image format is attached or if the glDrawBuffers information is invalid */
	GLenum status = glCheckFramebufferStatus (GL_FRAMEBUFFER);
	if (GL_FRAMEBUFFER_COMPLETE != status) {
		fprintf (stderr, "ERROR: incomplete framebuffer\n");
		if (GL_FRAMEBUFFER_UNDEFINED == status) {
			fprintf (stderr, "GL_FRAMEBUFFER_UNDEFINED\n");
		} else if (GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT == status) {
			fprintf (stderr, "GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT\n");
		} else if (GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT == status) {
			fprintf (stderr, "GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT\n");
		} else if (GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER == status) {
			fprintf (stderr, "GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER\n");
		} else if (GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER== status) {
			fprintf (stderr, "GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER\n");
		} else if (GL_FRAMEBUFFER_UNSUPPORTED == status) {
			fprintf (stderr, "GL_FRAMEBUFFER_UNSUPPORTED\n");
		} else if (GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE == status) {
			fprintf (stderr, "GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE\n");
		} else if (GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS == status) {
			fprintf (stderr, "GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS\n");
		} else {
			fprintf (stderr, "unspecified error\n");
		}
		return false;
	}
	
	/* re-bind the default framebuffer as a safe precaution */
	glBindFramebuffer (GL_FRAMEBUFFER, 0);
	return true;
}
Exemplo n.º 30
0
bool RenderTexture::initWithWidthAndHeight(int w, int h, Texture2D::PixelFormat format, GLuint depthStencilFormat)
{
    CCASSERT(format != Texture2D::PixelFormat::A8, "only RGB and RGBA formats are valid for a render texture");

    bool ret = false;
    void *data = nullptr;
    do 
    {
        _fullRect = _rtTextureRect = Rect(0,0,w,h);
        //Size size = Director::getInstance()->getWinSizeInPixels();
        //_fullviewPort = Rect(0,0,size.width,size.height);
        w = (int)(w * CC_CONTENT_SCALE_FACTOR());
        h = (int)(h * CC_CONTENT_SCALE_FACTOR());
        _fullviewPort = Rect(0,0,w,h);
        
        glGetIntegerv(GL_FRAMEBUFFER_BINDING, &_oldFBO);

        // textures must be power of two squared
        int powW = 0;
        int powH = 0;

        if (Configuration::getInstance()->supportsNPOT())
        {
            powW = w;
            powH = h;
        }
        else
        {
            powW = ccNextPOT(w);
            powH = ccNextPOT(h);
        }

        auto dataLen = powW * powH * 4;
        data = malloc(dataLen);
        CC_BREAK_IF(! data);

        memset(data, 0, dataLen);
        _pixelFormat = format;

        _texture = new Texture2D();
        if (_texture)
        {
            _texture->initWithData(data, dataLen, (Texture2D::PixelFormat)_pixelFormat, powW, powH, Size((float)w, (float)h));
        }
        else
        {
            break;
        }
        GLint oldRBO;
        glGetIntegerv(GL_RENDERBUFFER_BINDING, &oldRBO);
        
        if (Configuration::getInstance()->checkForGLExtension("GL_QCOM"))
        {
            _textureCopy = new Texture2D();
            if (_textureCopy)
            {
                _textureCopy->initWithData(data, dataLen, (Texture2D::PixelFormat)_pixelFormat, powW, powH, Size((float)w, (float)h));
            }
            else
            {
                break;
            }
        }

        // generate FBO
        glGenFramebuffers(1, &_FBO);
        glBindFramebuffer(GL_FRAMEBUFFER, _FBO);

        // associate texture with FBO
        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, _texture->getName(), 0);

        if (depthStencilFormat != 0)
        {
            //create and attach depth buffer
            glGenRenderbuffers(1, &_depthRenderBufffer);
            glBindRenderbuffer(GL_RENDERBUFFER, _depthRenderBufffer);
            glRenderbufferStorage(GL_RENDERBUFFER, depthStencilFormat, (GLsizei)powW, (GLsizei)powH);
            glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, _depthRenderBufffer);

            // if depth format is the one with stencil part, bind same render buffer as stencil attachment
            if (depthStencilFormat == GL_DEPTH24_STENCIL8)
            {
                glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, _depthRenderBufffer);
            }
        }

        // check if it worked (probably worth doing :) )
        CCASSERT(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE, "Could not attach texture to framebuffer");

        _texture->setAliasTexParameters();

        // retained
        setSprite(Sprite::createWithTexture(_texture));

        _texture->release();
        _sprite->setFlippedY(true);

        _sprite->setBlendFunc( BlendFunc::ALPHA_PREMULTIPLIED );

        glBindRenderbuffer(GL_RENDERBUFFER, oldRBO);
        glBindFramebuffer(GL_FRAMEBUFFER, _oldFBO);
        
        // Diabled by default.
        _autoDraw = false;
        
        // add sprite for backward compatibility
        addChild(_sprite);
        
        ret = true;
    } while (0);
    
    CC_SAFE_FREE(data);
    
    return ret;
}