// 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);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);

    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*2, SCR_HEIGHT*2);

    // Setup some OpenGL options
    glEnable(GL_DEPTH_TEST);

    // Setup and compile our shaders
    Shader shader("shaders/advanced_lighting.vs", "shaders/advanced_lighting.frag");

    GLfloat planeVertices[] = {
        // Positions          // Normals         // Texture Coords
        8.0f, -0.5f,  8.0f,  0.0f, 1.0f, 0.0f,  5.0f, 0.0f,
        -8.0f, -0.5f,  8.0f,  0.0f, 1.0f, 0.0f,  0.0f, 0.0f,
        -8.0f, -0.5f, -8.0f,  0.0f, 1.0f, 0.0f,  0.0f, 5.0f,

        8.0f, -0.5f,  8.0f,  0.0f, 1.0f, 0.0f,  5.0f, 0.0f,
        -8.0f, -0.5f, -8.0f,  0.0f, 1.0f, 0.0f,  0.0f, 5.0f,
        8.0f, -0.5f, -8.0f,  0.0f, 1.0f, 0.0f,  5.0f, 5.0f
    };
    // Setup plane VAO
    GLuint planeVAO, planeVBO;
    glGenVertexArrays(1, &planeVAO);
    glGenBuffers(1, &planeVBO);
    glBindVertexArray(planeVAO);
    glBindBuffer(GL_ARRAY_BUFFER, planeVBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(planeVertices), &planeVertices, GL_STATIC_DRAW);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)0);
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
    glEnableVertexAttribArray(2);
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(6 * sizeof(GLfloat)));
    glBindVertexArray(0);

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

    // Load textures
    GLuint floorTexture = loadTexture("resources/textures/wood.png");

    /*-------------------Load models--------------------*/

    Model ourModel("resources/objects/nanosuit/nanosuit.obj");
    Shader model_shader("shaders/model_shader.vs", "shaders/model_shader.frag");

    /*--------------------------------------------------*/

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

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

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

        // Draw objects
        shader.Use();
        glm::mat4 view = camera.GetViewMatrix();
        glm::mat4 projection = glm::perspective(camera.Zoom, (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f);
        glUniformMatrix4fv(glGetUniformLocation(shader.Program, "view"), 1, GL_FALSE, glm::value_ptr(view));
        glUniformMatrix4fv(glGetUniformLocation(shader.Program, "projection"), 1, GL_FALSE, glm::value_ptr(projection));
        // Set light uniforms
        glUniform3fv(glGetUniformLocation(shader.Program, "lightPos"), 1, &lightPos[0]);
        glUniform3fv(glGetUniformLocation(shader.Program, "viewPos"), 1, &camera.Position[0]);
        glUniform1i(glGetUniformLocation(shader.Program, "blinn"), blinn);
        // Floor
        glBindVertexArray(planeVAO);
        glBindTexture(GL_TEXTURE_2D, floorTexture);
        glDrawArrays(GL_TRIANGLES, 0, 6);
        glBindVertexArray(0);

        model_shader.Use();
        // Transformation matrices
        glUniformMatrix4fv(glGetUniformLocation(model_shader.Program, "projection"), 1, GL_FALSE, glm::value_ptr(projection));
        glUniformMatrix4fv(glGetUniformLocation(model_shader.Program, "view"), 1, GL_FALSE, glm::value_ptr(view));

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


        //std::cout << (blinn ? "true" : "false") << std::endl;

        // Swap the buffers
        glfwSwapBuffers(window);
    }

    glfwTerminate();
    return 0;
}
Beispiel #2
0
void CRenderer::BufferData(GLenum target, GLsizeiptr size, const GLvoid* data, GLenum usage)
{
    glBufferData(target, size, data, usage);
    FC_CHECK_GL_ERROR_DEBUG();
}
Beispiel #3
0
	BufferSubData(u32 type, u32 size) : StreamBuffer(type, size) {
		glBindBuffer(m_buffertype, m_buffer);
		glBufferData(m_buffertype, size, nullptr, GL_STATIC_DRAW);
		m_pointer = new u8[m_size];
	}
Beispiel #4
0
	MapAndOrphan(u32 type, u32 size) : StreamBuffer(type, size) {
		glBindBuffer(m_buffertype, m_buffer);
		glBufferData(m_buffertype, m_size, nullptr, GL_STREAM_DRAW);
	}
void OpenglBufferData::loadBufferData() {
	if (!theModelView)
		return;
	SimMesh *theMesh = theModelView->theMesh;
	MeshColor *theColor = theModelView->theColor;
	MeshTexture *theTexture = theModelView->theTexture;
	MeshNormal *theNormals = theModelView->theNormals;
	vertex *data = NULL;
	glGenVertexArrays(1, &vao);
	glBindVertexArray(vao);
	glGenBuffers(1, &vbo);
	glBindBuffer(GL_ARRAY_BUFFER, vbo);
	if (!theTexture) {
		data = new vertex[theMesh->numVertices()];
		for (size_t i = 0; i < theMesh->numVertices(); i++) {
			data[i].position = vec4(theMesh->indVertex(i)->p[0], theMesh->indVertex(i)->p[1], theMesh->indVertex(i)->p[2], 1.0f);
			if (theModelView->theColor) {
				GLfloat a = 1.0f;
				if (i < theColor->a.size()) a = theColor->a[i] / 255.0f;
				data[i].color = vec4(theColor->r[i] / 255.0f, theColor->g[i] / 255.0f, theColor->b[i] / 255.0f, a);
			}
			else
				data[i].color = vec4(theModelView->color[0], theModelView->color[1], theModelView->color[2], 1.0f);
		}
		if (theNormals) {
			for (size_t i = 0; i < theNormals->vNormals.size(); i++) {
				data[i].normal = vec3(theNormals->vNormals[i][0], theNormals->vNormals[i][1], theNormals->vNormals[i][2]);
			}
		}
		glBufferData(GL_ARRAY_BUFFER, theMesh->numVertices() * sizeof(vertex), data, GL_STATIC_DRAW);
	}
	else {
		// if texture exists, we need to duplicate the vertex on each triangle
		data = new vertex[theMesh->numFaces() * 3];
		for (size_t i = 0; i < theMesh->numFaces(); i++) {
			SimFace *f = theMesh->indFace(i);
			for (int j = 0; j < 3; j++) {
				SimVertex *v = f->ver[j];
				data[i * 3 + j].position = vec4(theMesh->indVertex(v->idx)->p[0], theMesh->indVertex(v->idx)->p[1], theMesh->indVertex(v->idx)->p[2], 1.0);
				if (theNormals) {
					data[i * 3 + j].normal = vec3(theNormals->vNormals[v->idx][0], theNormals->vNormals[v->idx][1], theNormals->vNormals[v->idx][2]);
					data[i * 3 + j].tangent = vec3(theModelView->tangents[i * 3 + j][0], theModelView->tangents[i * 3 + j][1], theModelView->tangents[i * 3 + j][2]);
				}
				data[i * 3 + j].texCoord = vec2(theTexture->getU(v, f), theTexture->getV(v, f));
			}
		}
		glBufferData(GL_ARRAY_BUFFER, 3 * theMesh->numFaces() * sizeof(vertex), data, GL_STATIC_DRAW);
	}

	glEnableVertexAttribArray(0);
	glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(vertex), BUFFER_OFFSET(0));
	if (theTexture) {
		glEnableVertexAttribArray(3);
		glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, sizeof(vertex), BUFFER_OFFSET(2 * sizeof(vec4) + sizeof(vec3)));
		if (theNormals) {
			glEnableVertexAttribArray(4);
			glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, sizeof(vertex), BUFFER_OFFSET(2 * sizeof(vec4) + sizeof(vec3) + sizeof(vec2)));
		}
	}
	else {
		glEnableVertexAttribArray(1);
		glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(vertex), BUFFER_OFFSET(sizeof(vec4)));
	}
	if (theNormals) {
		glEnableVertexAttribArray(2);
		glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(vertex), BUFFER_OFFSET(2 * sizeof(vec4)));
	}
	unsigned int *face_indices = new unsigned int[3 * theMesh->numFaces()];
	for (size_t i = 0; i < theMesh->numFaces(); i++) {
		SimFace *f = theMesh->indFace(i);
		for (int j = 0; j < 3; j++) {
			if (!theTexture) 
				face_indices[3 * i + j] = f->ver[j]->idx;
			else 
				face_indices[3 * i + j] = 3 * i + j;
		}
	}
	glGenBuffers(1, &vbo_face_indices);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo_face_indices);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, 3 * theMesh->numFaces() * sizeof(unsigned int), face_indices, GL_STATIC_DRAW);
	glGenVertexArrays(1, &vao_wireFrame);
	glBindVertexArray(vao_wireFrame);
	glBindBuffer(GL_ARRAY_BUFFER, vbo);
	glEnableVertexAttribArray(0);
	glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(vertex), BUFFER_OFFSET(0));
	unsigned int *edge_indices = new unsigned int[2 * theMesh->numEdges()];
	if (theTexture) {
		for (size_t i = 0; i < theMesh->numFaces(); i++) {
			SimFace *f = theMesh->indFace(i);
			for (int j = 0; j < 3; j++) {
				SimEdge * e = theMesh->idEdge(f->ver[j]->idx, f->ver[(j + 1) % 3]->idx);
				edge_indices[2 * e->idx + 0] = i * 3 + j;
				edge_indices[2 * e->idx + 1] = i * 3 + (j + 1) % 3;
			}
		}
	}
	else {
		for (size_t i = 0; i < theMesh->numEdges(); i++) {
			SimEdge * e = theMesh->indEdge(i);
			edge_indices[2 * i + 0] = e->v0->idx;
			edge_indices[2 * i + 1] = e->v1->idx;
		}
	}
	
	glGenBuffers(1, &vbo_edge_indices);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo_edge_indices);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, 2 * theMesh->numEdges() * sizeof(unsigned int), edge_indices, GL_STATIC_DRAW);
	if (theTexture) {
		glGenTextures(1, &texture);
		glBindTexture(GL_TEXTURE_2D, texture);
			//get the OpenGL-friendly image
		QImage GL_formatted_image = QGLWidget::convertToGLFormat(QImage(theModelView->theTexture->texture_filename.c_str()));
		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_LINEAR);
		glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
					//generate the texture
		glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, GL_formatted_image.width(),
		GL_formatted_image.height(),
		0, GL_RGBA, GL_UNSIGNED_BYTE, GL_formatted_image.bits() );
		glBindTexture(GL_TEXTURE_2D, 0);
		//QImage GL_formatted_image2 = QGLWidget::convertToGLFormat(QImage("normal.bmp"));
		//glGenTextures(1, &normalTexture);
		//glBindTexture(GL_TEXTURE_2D, normalTexture);
		////get the OpenGL-friendly image
		//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_LINEAR);
		//glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		////generate the texture
		//glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, GL_formatted_image2.width(),
		//	GL_formatted_image2.height(),
		//	0, GL_RGBA, GL_UNSIGNED_BYTE, GL_formatted_image2.bits() );
		//glBindTexture(GL_TEXTURE_2D, 0);
		
	}

	delete []data;
	delete []edge_indices;
	delete []face_indices;
}
Beispiel #6
0
bool
OsdGLDrawContext::allocate(FarMesh<OsdVertex> *farMesh,
                           GLuint vbo,
                           int numElements,
                           bool requirePtexCoordinates,
                           bool requireFVarData)
{
    FarPatchTables const * patchTables = farMesh->GetPatchTables();

    if (not patchTables) {
        // uniform patches
        isAdaptive = false;

        // XXX: farmesh should have FarDensePatchTable for dense mesh indices.
        //      instead of GetFaceVertices().
        const FarSubdivisionTables<OsdVertex> *tables = farMesh->GetSubdivisionTables();
        int level = tables->GetMaxLevel();
        const std::vector<int> &indices = farMesh->GetFaceVertices(level-1);

        // XXX: farmesh or FarSubdivisionTables should have a virtual method
        // to determine loop or not
        bool loop =
            dynamic_cast<const FarLoopSubdivisionTables<OsdVertex>*>(tables) != NULL;

        int numIndices = (int)indices.size();

        // Allocate and fill index buffer.
        glGenBuffers(1, &patchIndexBuffer);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, patchIndexBuffer);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER,
                     numIndices * sizeof(unsigned int), &(indices[0]), GL_STATIC_DRAW);

        OsdPatchArray array;
        array.desc.type = kNonPatch;
        array.patchSize = loop ? 3 : 4;
        array.firstIndex = 0;
        array.numIndices = numIndices;

        patchArrays.push_back(array);

        // Allocate ptex coordinate buffer if requested (for non-adaptive)
        if (requirePtexCoordinates) {
            GLuint ptexCoordinateBuffer = 0;
            glGenTextures(1, &ptexCoordinateTextureBuffer);
            glGenBuffers(1, &ptexCoordinateBuffer);
            glBindBuffer(GL_TEXTURE_BUFFER, ptexCoordinateBuffer);

            const std::vector<int> &ptexCoordinates =
                farMesh->GetPtexCoordinates(level-1);
            int size = (int)ptexCoordinates.size() * sizeof(GLint);

            glBufferData(GL_TEXTURE_BUFFER, size, &(ptexCoordinates[0]), GL_STATIC_DRAW);

            glBindTexture(GL_TEXTURE_BUFFER, ptexCoordinateTextureBuffer);
            glTexBuffer(GL_TEXTURE_BUFFER, GL_RG32I, ptexCoordinateBuffer);
            glDeleteBuffers(1, &ptexCoordinateBuffer);
            glBindTexture(GL_TEXTURE_BUFFER, 0);
        }

        // Allocate fvar data buffer if requested (for non-adaptive)
        if (requireFVarData) {
            GLuint fvarDataBuffer = 0;
            glGenTextures(1, &fvarDataTextureBuffer);
            glGenBuffers(1, &fvarDataBuffer);
            glBindBuffer(GL_TEXTURE_BUFFER, fvarDataBuffer);

            const std::vector<float> &fvarData = farMesh->GetFVarData(level-1);
            int size = (int)fvarData.size() * sizeof(float);

            glBufferData(GL_TEXTURE_BUFFER, size, &(fvarData[0]), GL_STATIC_DRAW);

            glBindTexture(GL_TEXTURE_BUFFER, fvarDataTextureBuffer);
            glTexBuffer(GL_TEXTURE_BUFFER, GL_R32F, fvarDataBuffer);
            glDeleteBuffers(1, &fvarDataBuffer);
            glBindTexture(GL_TEXTURE_BUFFER, 0);
        }

        return true;
    }

    // adaptive patches
    isAdaptive = true;

    // Determine buffer sizes
    int totalPatchIndices = 
        patchTables->GetFullRegularPatches().GetSize() +
        patchTables->GetFullBoundaryPatches().GetSize() +
        patchTables->GetFullCornerPatches().GetSize() +
        patchTables->GetFullGregoryPatches().GetSize() +
        patchTables->GetFullBoundaryGregoryPatches().GetSize();

    int totalPatchLevels = 
        patchTables->GetFullRegularPatches().GetSize()/patchTables->GetRegularPatchRingsize() +
        patchTables->GetFullBoundaryPatches().GetSize()/patchTables->GetBoundaryPatchRingsize() +
        patchTables->GetFullCornerPatches().GetSize()/patchTables->GetCornerPatchRingsize() +
        patchTables->GetFullGregoryPatches().GetSize()/patchTables->GetGregoryPatchRingsize() +
        patchTables->GetFullBoundaryGregoryPatches().GetSize()/patchTables->GetGregoryPatchRingsize();

    for (int p=0; p<5; ++p) {
        totalPatchIndices +=
            patchTables->GetTransitionRegularPatches(p).GetSize();

        totalPatchLevels +=
            patchTables->GetTransitionRegularPatches(p).GetSize()/patchTables->GetRegularPatchRingsize();

        for (int r=0; r<4; ++r) {
            totalPatchIndices +=
                patchTables->GetTransitionBoundaryPatches(p, r).GetSize() +
                patchTables->GetTransitionCornerPatches(p, r).GetSize();

            totalPatchLevels +=
                patchTables->GetTransitionBoundaryPatches(p, r).GetSize()/patchTables->GetBoundaryPatchRingsize() +
                patchTables->GetTransitionCornerPatches(p, r).GetSize()/patchTables->GetCornerPatchRingsize();
        }
    }

    // Allocate and fill index buffer.
    glGenBuffers(1, &patchIndexBuffer);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, patchIndexBuffer);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER,
        totalPatchIndices * sizeof(unsigned int), NULL, GL_STATIC_DRAW);

    GLuint patchLevelBuffer = 0;
    glGenBuffers(1, &patchLevelBuffer);
    glBindBuffer(GL_TEXTURE_BUFFER, patchLevelBuffer);
    glBufferData(GL_TEXTURE_BUFFER,
        totalPatchLevels * sizeof(unsigned char), NULL, GL_STATIC_DRAW);

    // Allocate ptex coordinate buffer if requested
    GLuint ptexCoordinateBuffer = 0;
    if (requirePtexCoordinates) {
        glGenTextures(1, &ptexCoordinateTextureBuffer);
        glGenBuffers(1, &ptexCoordinateBuffer);
        glBindBuffer(GL_ARRAY_BUFFER, ptexCoordinateBuffer);
        glBufferData(GL_ARRAY_BUFFER,
            totalPatchLevels * sizeof(int) * 2, NULL, GL_STATIC_DRAW);
    }

    // Allocate fvar data buffer if requested
    GLuint fvarDataBuffer = 0;
    if (requireFVarData) {
        glGenTextures(1, &fvarDataTextureBuffer);
        glGenBuffers(1, &fvarDataBuffer);
        glBindBuffer(GL_UNIFORM_BUFFER, fvarDataBuffer);
        glBufferData(GL_UNIFORM_BUFFER,
            totalPatchLevels * sizeof(float) * farMesh->GetTotalFVarWidth()*4, NULL, GL_STATIC_DRAW);
    }

    int indexBase = 0;
    int levelBase = 0;
    int maxValence = patchTables->GetMaxValence();

    _AppendPatchArray(&indexBase, &levelBase,
                        patchTables->GetFullRegularPatches(),
                        patchTables->GetRegularPatchRingsize(),
                        patchTables->GetFullRegularPtexCoordinates(),
                        patchTables->GetFullRegularFVarData(),
                        farMesh->GetTotalFVarWidth(),
                        OsdPatchDescriptor(kRegular, 0, 0, 0, 0), 0);
    _AppendPatchArray(&indexBase, &levelBase,
                        patchTables->GetFullBoundaryPatches(),
                        patchTables->GetBoundaryPatchRingsize(),
                        patchTables->GetFullBoundaryPtexCoordinates(),
                        patchTables->GetFullBoundaryFVarData(),
                        farMesh->GetTotalFVarWidth(),
                        OsdPatchDescriptor(kBoundary, 0, 0, 0, 0), 0);
    _AppendPatchArray(&indexBase, &levelBase,
                        patchTables->GetFullCornerPatches(),
                        patchTables->GetCornerPatchRingsize(),
                        patchTables->GetFullCornerPtexCoordinates(),
                        patchTables->GetFullCornerFVarData(),
                        farMesh->GetTotalFVarWidth(),
                        OsdPatchDescriptor(kCorner, 0, 0, 0, 0), 0);
    _AppendPatchArray(&indexBase, &levelBase,
                        patchTables->GetFullGregoryPatches(),
                        patchTables->GetGregoryPatchRingsize(),
                        patchTables->GetFullGregoryPtexCoordinates(),
                        patchTables->GetFullGregoryFVarData(),
                        farMesh->GetTotalFVarWidth(),
                        OsdPatchDescriptor(kGregory, 0, 0,
                                           maxValence, numElements), 0);
    _AppendPatchArray(&indexBase, &levelBase,
                        patchTables->GetFullBoundaryGregoryPatches(),
                        patchTables->GetGregoryPatchRingsize(),
                        patchTables->GetFullBoundaryGregoryPtexCoordinates(),
                        patchTables->GetFullBoundaryGregoryFVarData(),
                        farMesh->GetTotalFVarWidth(),
                        OsdPatchDescriptor(kBoundaryGregory, 0, 0,
                                           maxValence, numElements),
                        (int)patchTables->GetFullGregoryPatches().GetSize());

    for (int p=0; p<5; ++p) {
        _AppendPatchArray(&indexBase, &levelBase,
                        patchTables->GetTransitionRegularPatches(p),
                        patchTables->GetRegularPatchRingsize(),
                        patchTables->GetTransitionRegularPtexCoordinates(p),
                        patchTables->GetTransitionRegularFVarData(p),
                        farMesh->GetTotalFVarWidth(),
                        OsdPatchDescriptor(kTransitionRegular, p, 0, 0, 0), 0);
        for (int r=0; r<4; ++r) {
            _AppendPatchArray(&indexBase, &levelBase,
                        patchTables->GetTransitionBoundaryPatches(p, r),
                        patchTables->GetBoundaryPatchRingsize(),
                        patchTables->GetTransitionBoundaryPtexCoordinates(p, r),
                        patchTables->GetTransitionBoundaryFVarData(p, r),
                        farMesh->GetTotalFVarWidth(),
                        OsdPatchDescriptor(kTransitionBoundary, p, r, 0, 0), 0);
            _AppendPatchArray(&indexBase, &levelBase,
                        patchTables->GetTransitionCornerPatches(p, r),
                        patchTables->GetCornerPatchRingsize(),
                        patchTables->GetTransitionCornerPtexCoordinates(p, r),
                        patchTables->GetTransitionCornerFVarData(p, r),
                        farMesh->GetTotalFVarWidth(),
                        OsdPatchDescriptor(kTransitionCorner, p, r, 0, 0), 0);
        }
    }

    // finalize level texture buffer
    glGenTextures(1, &patchLevelTextureBuffer);
    glBindTexture(GL_TEXTURE_BUFFER, patchLevelTextureBuffer);
    glTexBuffer(GL_TEXTURE_BUFFER, GL_R8I, patchLevelBuffer);
    glDeleteBuffers(1, &patchLevelBuffer);

    // finalize ptex coordinate texture buffer
    glBindBuffer(GL_ARRAY_BUFFER, 0);
    if (requirePtexCoordinates) {
        glBindTexture(GL_TEXTURE_BUFFER, ptexCoordinateTextureBuffer);
        glTexBuffer(GL_TEXTURE_BUFFER, GL_RG32I, ptexCoordinateBuffer);
        glDeleteBuffers(1, &ptexCoordinateBuffer);
    }
    // finalize fvar data texture buffer
    glBindBuffer(GL_UNIFORM_BUFFER, 0);
    if (requireFVarData) {
        glBindTexture(GL_TEXTURE_BUFFER, fvarDataTextureBuffer);
        glTexBuffer(GL_TEXTURE_BUFFER, GL_R32F, fvarDataBuffer);
        glDeleteBuffers(1, &fvarDataBuffer);
    }

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
    glBindBuffer(GL_TEXTURE_BUFFER, 0);

    // allocate and initialize additional buffer data
    FarPatchTables::VertexValenceTable const &
        valenceTable = patchTables->GetVertexValenceTable();

    if (not valenceTable.empty()) {
        GLuint buffer = 0;
        glGenBuffers(1, &buffer);
        glBindBuffer(GL_TEXTURE_BUFFER, buffer);
        glBufferData(GL_TEXTURE_BUFFER,
                valenceTable.size() * sizeof(unsigned int),
                &valenceTable[0], GL_STATIC_DRAW);

        glGenTextures(1, &vertexValenceTextureBuffer);
        glBindTexture(GL_TEXTURE_BUFFER, vertexValenceTextureBuffer);
        glTexBuffer(GL_TEXTURE_BUFFER, GL_R32I, buffer);
        glDeleteBuffers(1, &buffer);

        glGenTextures(1, &vertexTextureBuffer);
        glBindTexture(GL_TEXTURE_BUFFER, vertexTextureBuffer);
        glTexBuffer(GL_TEXTURE_BUFFER, GL_R32F, vbo);

        glBindBuffer(GL_TEXTURE_BUFFER, 0);
    }

    FarPatchTables::QuadOffsetTable const &
        quadOffsetTable = patchTables->GetQuadOffsetTable();

    if (not quadOffsetTable.empty()) {
        GLuint buffer = 0;
        glGenBuffers(1, &buffer);
        glBindBuffer(GL_TEXTURE_BUFFER, buffer);
        glBufferData(GL_TEXTURE_BUFFER,
                quadOffsetTable.size() * sizeof(unsigned int),
                &quadOffsetTable[0], GL_STATIC_DRAW);

        glGenTextures(1, &quadOffsetTextureBuffer);
        glBindTexture(GL_TEXTURE_BUFFER, quadOffsetTextureBuffer);
        glTexBuffer(GL_TEXTURE_BUFFER, GL_R32I, buffer);
        glDeleteBuffers(1, &buffer);

        glBindBuffer(GL_TEXTURE_BUFFER, 0);
    }

    return true;
}
Beispiel #7
0
int main() {
  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);
#ifdef __APPLE__
  glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif
  
  GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "EX_GS_S_1", nullptr, nullptr);
  if (window == nullptr) {
    std::cout << "Create window failed" << std::endl;
    glfwTerminate();
    return -1;
  }
  glfwMakeContextCurrent(window);
  glfwSetKeyCallback(window, key_callback);
  
  glewExperimental = GL_TRUE;
  if (glewInit() != GLEW_OK) {
    std::cout << "Init GLEW failed" << std::endl;
    glfwTerminate();
    return -1;
  }
  
  int width, height;
  glfwGetFramebufferSize(window, &width, &height);
  glViewport(0, 0, width, height);
  
  ShaderReader shader("/Users/king/git/LearningOpenGL/Files/Exercises/Getting Start/Shader/2/EX_GS_S_2_Vertex.shader", "/Users/king/git/LearningOpenGL/Files/Exercises/Getting Start/Shader/2/EX_GS_S_2_Fragment.shader");
  
  GLfloat vertices[] = {
    0.5f, -0.5f, 0.0f,
    -0.5f, -0.5f, 0.0f,
    0.0f, 0.5f, 0.0f,
  };
  
  GLuint VAO, VBO;
  glGenVertexArrays(1, &VAO);
  glGenBuffers(1, &VBO);
  glBindVertexArray(VAO);
  glBindBuffer(GL_ARRAY_BUFFER, VBO);
  glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
  glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GL_FLOAT), (GLvoid*)0);
  glEnableVertexAttribArray(0);
  glBindBuffer(GL_ARRAY_BUFFER, 0);
  glBindVertexArray(0);
  
  while (!glfwWindowShouldClose(window)) {
    glfwPollEvents();
    
    glClearColor(0.3f, 0.2f, 0.2f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);
    
    shader.Use();
    GLfloat timeVal = glfwGetTime();
    GLfloat posVal = (sin(timeVal)) + 0.5f;
    glUniform1f(glGetUniformLocation(shader.GetProgram(), "x"), posVal);
    std::cout << posVal << std::endl;
    shader.Use();
    
    glBindVertexArray(VAO);
    glDrawArrays(GL_TRIANGLES, 0, 3);
    glBindVertexArray(0);
    
    glfwSwapBuffers(window);
  }
  
  glDeleteBuffers(1, &VBO);
  glDeleteVertexArrays(1, &VAO);
  
  glfwTerminate();
  return 0;
}
Beispiel #8
0
GLUSuint initWaterTexture(GLUSfloat waterPlaneLength)
{
    GLfloat projectionMatrixWaterTexture[16];
    GLfloat modelViewMatrixWaterTexture[16];

	GLUSshape plane;

	GLUStextfile vertexSource;
	GLUStextfile fragmentSource;

	glusLoadTextFile("../Example15/shader/WaterTexture.vert.glsl", &vertexSource);
	glusLoadTextFile("../Example15/shader/WaterTexture.frag.glsl", &fragmentSource);

	glusBuildProgramFromSource(&g_programWaterTexture, (const GLUSchar**) &vertexSource.text, 0, 0, 0, (const GLUSchar**) &fragmentSource.text);

	glusDestroyTextFile(&vertexSource);
	glusDestroyTextFile(&fragmentSource);

	//

    g_projectionMatrixWaterTextureLocation = glGetUniformLocation(g_programWaterTexture.program, "u_projectionMatrix");
    g_modelViewMatrixWaterTextureLocation = glGetUniformLocation(g_programWaterTexture.program, "u_modelViewMatrix");

    g_waterPlaneLengthWaterTextureLocation = glGetUniformLocation(g_programWaterTexture.program, "u_waterPlaneLength");
    g_passedTimeWaterTextureLocation = glGetUniformLocation(g_programWaterTexture.program, "u_passedTime");
    g_waveParametersWaterTextureLocation = glGetUniformLocation(g_programWaterTexture.program, "u_waveParameters");
    g_waveDirectionsWaterTextureLocation = glGetUniformLocation(g_programWaterTexture.program, "u_waveDirections");

    g_vertexWaterTextureLocation = glGetAttribLocation(g_programWaterTexture.program, "a_vertex");
    g_texCoordWaterTextureLocation = glGetAttribLocation(g_programWaterTexture.program, "a_texCoord");

	//

    glGenTextures(1, &g_mirrorTexture);
    glActiveTexture(GL_TEXTURE1);
    glBindTexture(GL_TEXTURE_2D, g_mirrorTexture);

    glTexImage2D(GL_TEXTURE_2D, 0, GLUS_RGB, TEXTURE_SIZE, TEXTURE_SIZE, 0, GLUS_RGB, GL_UNSIGNED_BYTE, 0);

    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, 0);

    //

    glGenRenderbuffers(1, &g_depthMirrorTexture);
    glBindRenderbuffer(GL_RENDERBUFFER, g_depthMirrorTexture);
    glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, TEXTURE_SIZE, TEXTURE_SIZE);

    glBindRenderbuffer(GL_RENDERBUFFER, 0);

    //

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

    // Attach the color buffer ...
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, g_mirrorTexture, 0);

    // ... and the depth buffer,
    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, g_depthMirrorTexture);

    if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
    {
        printf("GL_FRAMEBUFFER_COMPLETE error 0x%x", glCheckFramebufferStatus(GL_FRAMEBUFFER));

        return GLUS_FALSE;
    }

    glBindFramebuffer(GL_FRAMEBUFFER, 0);

    //

    glBindVertexArray(0);

    //

	glusCreatePlanef(&plane, TEXTURE_SIZE / 2.0f);
	g_numberIndicesWaterTexture = plane.numberIndices;

	glGenBuffers(1, &g_verticesWaterTextureVBO);
	glBindBuffer(GL_ARRAY_BUFFER, g_verticesWaterTextureVBO);
	glBufferData(GL_ARRAY_BUFFER, plane.numberVertices * 4 * sizeof(GLfloat), (GLfloat*) plane.vertices, GL_STATIC_DRAW);

	glGenBuffers(1, &g_texCoordsWaterTextureVBO);
	glBindBuffer(GL_ARRAY_BUFFER, g_texCoordsWaterTextureVBO);
	glBufferData(GL_ARRAY_BUFFER, plane.numberVertices * 2 * sizeof(GLfloat), (GLfloat*) plane.texCoords, GL_STATIC_DRAW);

	glBindBuffer(GL_ARRAY_BUFFER, 0);

	glGenBuffers(1, &g_indicesWaterTextureVBO);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_indicesWaterTextureVBO);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, plane.numberIndices * sizeof(GLuint), (GLuint*) plane.indices, GL_STATIC_DRAW);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

	glusDestroyShapef(&plane);

	//

    glUseProgram(g_programWaterTexture.program);

	glusLookAtf(modelViewMatrixWaterTexture, 0.0f, 0.0f, 5.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f);
	glUniformMatrix4fv(g_modelViewMatrixWaterTextureLocation, 1, GL_FALSE, modelViewMatrixWaterTexture);

	glusOrthof(projectionMatrixWaterTexture, -(GLfloat) TEXTURE_SIZE / 2, (GLfloat) TEXTURE_SIZE / 2, -(GLfloat) TEXTURE_SIZE / 2, (GLfloat) TEXTURE_SIZE / 2, 1.0f, 100.0f);
    glUniformMatrix4fv(g_projectionMatrixWaterTextureLocation, 1, GL_FALSE, projectionMatrixWaterTexture);

	glUniform1f(g_waterPlaneLengthWaterTextureLocation, waterPlaneLength);

	//

    glGenVertexArrays(1, &g_vaoWaterTexture);
    glBindVertexArray(g_vaoWaterTexture);

	glBindBuffer(GL_ARRAY_BUFFER, g_verticesWaterTextureVBO);
	glVertexAttribPointer(g_vertexWaterTextureLocation, 4, GL_FLOAT, GL_FALSE, 0, 0);
	glEnableVertexAttribArray(g_vertexWaterTextureLocation);

	glBindBuffer(GL_ARRAY_BUFFER, g_texCoordsWaterTextureVBO);
	glVertexAttribPointer(g_texCoordWaterTextureLocation, 2, GL_FLOAT, GL_FALSE, 0, 0);
	glEnableVertexAttribArray(g_texCoordWaterTextureLocation);

	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_indicesWaterTextureVBO);

	//

    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

    glClearDepth(1.0f);

    glEnable(GL_DEPTH_TEST);

    glEnable(GL_CULL_FACE);

	return g_mirrorTexture;
}
Beispiel #9
0
_JATTA_EXPORT void Jatta::OpenGL::Buffer::Data(Size size, void* data, Enum usage)
{
    glBufferData(this->type, size, data, usage);
    GLCHECK("Failed to set buffer data.");
}
Beispiel #10
0
void			Text::LoadFont(GLfloat width, GLfloat height)
{
	shader = new Shader( (pathToShaders + "Text.vert").c_str(),
				  		 (pathToShaders + "Text.frag").c_str());
	shader->Use();
    glm::mat4 projection = glm::ortho(0.0f, width, 0.0f, height);
    glUniformMatrix4fv(glGetUniformLocation(shader->Program, "projection"), 1, GL_FALSE, glm::value_ptr(projection));

	if(FT_Init_FreeType(&freetype))
		throw DError() << msg("Could not init freetype library");
	if(FT_New_Face(freetype, (pathToFont + font).c_str(), 0, &face))
		throw DError() << msg("Could not open font: " + font);
	
	FT_Set_Pixel_Sizes(face, 0, size);
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1); 

	for (GLubyte c = 0; c < 128; c++)
    {
        // Load character glyph 
        if (FT_Load_Char(face, c, FT_LOAD_RENDER))
        {
            std::cout << "ERROR::FREETYTPE: Failed to load Glyph" << std::endl;
            continue;
        }
        // Generate texture
        GLuint texture;
        glGenTextures(1, &texture);
        glBindTexture(GL_TEXTURE_2D, texture);
        glTexImage2D(
            GL_TEXTURE_2D,
            0,
            GL_RED,
            face->glyph->bitmap.width,
            face->glyph->bitmap.rows,
            0,
            GL_RED,
            GL_UNSIGNED_BYTE,
            face->glyph->bitmap.buffer
        );
        // Set texture options
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        // Now store character for later use
        Character character = {
            texture,
            glm::ivec2(face->glyph->bitmap.width, face->glyph->bitmap.rows),
            glm::ivec2(face->glyph->bitmap_left, face->glyph->bitmap_top),
            (GLuint)face->glyph->advance.x
        };
        Characters.insert(std::pair<GLchar, Character>(c, character));
    }
    glBindTexture(GL_TEXTURE_2D, 0);
    // Destroy FreeType once we're finished
    FT_Done_Face(face);
    FT_Done_FreeType(freetype);

    
    // Configure VAO/VBO for texture quads
    glGenVertexArrays(1, &VAO);
    glGenBuffers(1, &VBO);
    glBindVertexArray(VAO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 6 * 4, NULL, GL_DYNAMIC_DRAW);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), 0);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glBindVertexArray(0);
}
Beispiel #11
0
void nullspace_init(void) {
  GLint vs = create_shader(GL_VERTEX_SHADER, vs_src);
  GLint fs = create_shader(GL_FRAGMENT_SHADER, fs_src);
  shdr_prog = create_shader_program(2, vs, fs);

  glDeleteShader(vs);
  glDeleteShader(fs);

  glGenVertexArrays(1, &vtx_arr);
  glGenBuffers(1, &vtx_buf);

  glBindVertexArray(vtx_arr);
  {
    glBindBuffer(GL_ARRAY_BUFFER, vtx_buf);
    {
      glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec4) * num_verts, NULL,
                   GL_STATIC_DRAW);

      glm::vec4 *ptr = (glm::vec4 *)glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY);
      if (!ptr) {
        fprintf(stderr, "ERROR: failed to map null-space vertex buffer\n");
        exit(1);
      }

      // grid (GL_LINES)
      size_t idx = 0;
      for (int i = -sz; i < sz; ++i) {
        ptr[idx++] = glm::vec4(-sz, 0, i, 1);
        ptr[idx++] = glm::vec4(sz, 0, i, 1);

        ptr[idx++] = glm::vec4(i, 0, -sz, 1);
        ptr[idx++] = glm::vec4(i, 0, sz, 1);
      }

      // border line (GL_LINE_LOOP)
      ptr[idx++] = glm::vec4(-sz, 0, -sz, 1);
      ptr[idx++] = glm::vec4(-sz, 0, sz, 1);
      ptr[idx++] = glm::vec4(sz, 0, sz, 1);
      ptr[idx++] = glm::vec4(-sz, 0, sz, 1);

      /* axis lines (GL_LINES)*/

      // x-axis
      ptr[idx++] = glm::vec4(-sz, 0, 0, 1);
      ptr[idx++] = glm::vec4(sz, 0, 0, 1);

      // y-axis
      ptr[idx++] = glm::vec4(0, sz, 0, 1);
      ptr[idx++] = glm::vec4(0, 0, 0, 1);

      // z-axis
      ptr[idx++] = glm::vec4(0, 0, -sz, 1);
      ptr[idx++] = glm::vec4(0, 0, sz, 1);

      GLboolean result = glUnmapBuffer(GL_ARRAY_BUFFER);
      if (!result) {
        fprintf(stderr, "ERROR: failed to unmap null-space vertex buffer\n");
        exit(1);
      }
      ptr = NULL;

      glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, NULL);
    }
    glBindVertexArray(0);
  }
  glBindBuffer(GL_ARRAY_BUFFER, 0);

  // buffer lookup offsets upon render
  size_t offset = 0;
  for (uint32_t i(0); i < num_draw_arrays; ++i) {
    draw_array_t *draw_array = &draw_arrays[i];
    draw_array->first = offset;
    offset += draw_array->count;
  }
}
void C4FoWDrawLightTextureStrategy::End(C4ShaderCall& call)
{
	// If we have nothing to draw (e.g. directly after initialization), abort early.
	if (vertices.empty()) return;

	// Upload vertices
	glBindBuffer(GL_ARRAY_BUFFER, vbo);
	if (vbo_size < vertices.size())
	{
		glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(Vertex), &vertices[0], GL_DYNAMIC_DRAW);
		vbo_size = vertices.size();
	}
	else
	{
		glBufferSubData(GL_ARRAY_BUFFER, 0, vertices.size() * sizeof(Vertex), &vertices[0]);
	}

	// Region dimensions
	const float width = region->getSurfaceWidth();
	const float height = region->getSurfaceHeight() / 2.0;

	// Set Y offset for vertex
	float y_offset[] = { 0.0f, 0.0f };
	call.SetUniform2fv(C4FoWRSU_VertexOffset, 1, y_offset);

	// Enable scissor test to only draw in upper or lower half of texture
	glEnable(GL_SCISSOR_TEST);
	glScissor(0, height, width, height);

	// Setup state for 1st pass
	glEnableVertexAttribArray(call.GetAttribute(C4FoWRSA_Position));
	glEnableVertexAttribArray(call.GetAttribute(C4FoWRSA_Color));
	glVertexAttribPointer(call.GetAttribute(C4FoWRSA_Position), 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), reinterpret_cast<const uint8_t*>(offsetof(Vertex, x)));
	glVertexAttribPointer(call.GetAttribute(C4FoWRSA_Color), 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), reinterpret_cast<const uint8_t*>(offsetof(Vertex, r1)));

	// Set up blend equation, see C4FoWDrawLightTextureStrategy::DrawVertex
	// for details.
	glBlendFunc(GL_ONE, GL_ONE);
	glBlendEquationSeparate(GL_FUNC_ADD, GL_MAX);

	// Render 1st pass
	glDrawElements(GL_TRIANGLES, triangulator.GetNIndices(), GL_UNSIGNED_INT, triangulator.GetIndices());

	// Prepare state for 2nd pass
	glBlendFunc(GL_ONE, GL_ONE);
	glBlendEquation(GL_FUNC_REVERSE_SUBTRACT);
	glVertexAttribPointer(call.GetAttribute(C4FoWRSA_Color), 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), reinterpret_cast<const uint8_t*>(offsetof(Vertex, r2)));

	// Render 2nd pass
	glDrawElements(GL_TRIANGLES, triangulator.GetNIndices(), GL_UNSIGNED_INT, triangulator.GetIndices());

	// Prepare state for 3rd pass (color pass)
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glBlendEquation(GL_FUNC_ADD);
	glScissor(0, 0, width, height);
	glVertexAttribPointer(call.GetAttribute(C4FoWRSA_Color), 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), reinterpret_cast<const uint8_t*>(offsetof(Vertex, r3)));
	y_offset[1] = height;
	call.SetUniform2fv(C4FoWRSU_VertexOffset, 1, y_offset);
	
	// Render 3rd pass
	glDrawElements(GL_TRIANGLES, triangulator.GetNIndices(), GL_UNSIGNED_INT, triangulator.GetIndices());

	// Reset GL state
	glDisableVertexAttribArray(call.GetAttribute(C4FoWRSA_Position));
	glDisableVertexAttribArray(call.GetAttribute(C4FoWRSA_Color));
	glBindBuffer(GL_ARRAY_BUFFER, 0);
	glDisable(GL_SCISSOR_TEST);

	// Assume the capacity stays the same:
	vertices.resize(0);
	C4FoWDrawStrategy::End(call);
}
// The MAIN function, from here we start the application and run the game loop
int main()
{
    std::cout << "Starting GLFW context, OpenGL 4.3" << std::endl;
    // Init GLFW
    glfwInit();
    // Set all the required options for GLFW
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); //Doesn't let us use OpenGL's legacy functions
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

    // Create a GLFWwindow object that we can use for GLFW's functions
    GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr);
    if (window == nullptr)
    {
        std::cout << "Failed to create GLFW window" << std::endl;
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);
    // Set the required callback functions
    glfwSetKeyCallback(window, key_callback);

    // Set this to true so GLEW knows to use a modern approach to retrieving function pointers and extensions (use modern OpenGL)
    glewExperimental = GL_TRUE;
    // Initialize GLEW to setup the OpenGL Function pointers
    glewInit();

    // Define the viewport dimensions
    glViewport(0, 0, WIDTH, HEIGHT);

    // Build and compile our shader program
    // Vertex shader
    GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
    glCompileShader(vertexShader);
    // Check for compile time errors
    GLint success;
    GLchar infoLog[512];
    glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
    if (!success)
    {
        glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
        std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;
    }
    // Create two fragment shaders
    // Fragment shader 1
    GLuint fragmentShader1 = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragmentShader1, 1, &fragmentShaderSource1, NULL);
    glCompileShader(fragmentShader1);
    // Check for compile time errors
    glGetShaderiv(fragmentShader1, GL_COMPILE_STATUS, &success);
    if (!success)
    {
        glGetShaderInfoLog(fragmentShader1, 512, NULL, infoLog);
        std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::endl;
    }
    // Fragment shader 2
    GLuint fragmentShader2 = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragmentShader2, 1, &fragmentShaderSource2, NULL);
    glCompileShader(fragmentShader2);
    // Check for compile time errors
    glGetShaderiv(fragmentShader2, GL_COMPILE_STATUS, &success);
    if (!success)
    {
        glGetShaderInfoLog(fragmentShader2, 512, NULL, infoLog);
        std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::endl;
    }
    // Link shaders
    // Shader 1
    GLuint shaderProgram1 = glCreateProgram();
    glAttachShader(shaderProgram1, vertexShader);
    glAttachShader(shaderProgram1, fragmentShader1);
    glLinkProgram(shaderProgram1);
    // Check for linking errors
    glGetProgramiv(shaderProgram1, GL_LINK_STATUS, &success);
    if (!success) {
        glGetProgramInfoLog(shaderProgram1, 512, NULL, infoLog);
        std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << std::endl;
    }
    // Shader 2
    GLuint shaderProgram2 = glCreateProgram();
    glAttachShader(shaderProgram2, vertexShader);
    glAttachShader(shaderProgram2, fragmentShader2);
    glLinkProgram(shaderProgram2);
    // Check for linking errors
    glGetProgramiv(shaderProgram2, GL_LINK_STATUS, &success);
    if (!success) {
        glGetProgramInfoLog(shaderProgram2, 512, NULL, infoLog);
        std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << std::endl;
    }
    glDeleteShader(vertexShader);
    glDeleteShader(fragmentShader1);
    glDeleteShader(fragmentShader2);

    /*GLfloat vertices[] = {
        -0.5f, -0.5f, 0.0f,
         0.5f, -0.5f, 0.0f,
         0.0f,  0.5f, 0.0f
    };*/

    /*GLfloat vertices[] = {
         0.5f,  0.5f, 0.0f,  // Top Right
         0.5f, -0.5f, 0.0f,  // Bottom Right
        -0.5f, -0.5f, 0.0f,  // Bottom Left
        -0.5f,  0.5f, 0.0f   // Top Left
    };
    GLuint indices[] = {  // Note that we start from 0!
        0, 1, 3,  // First Triangle
        1, 2, 3   // Second Triangle
    };*/

    //Drawing two triangles
    ///////////////////////
    GLfloat vertices1[] = {
        // First triangle
        -0.8f, -0.4f, 0.0f,
        -0.4f,  0.4f, 0.0f,
         0.0f, -0.4f, 0.0f,
    };
    GLfloat vertices2[] = {
        // Second triangle
         0.0f, -0.4f, 0.0f,
         0.4f,  0.4f, 0.0f,
         0.8f, -0.4f, 0.0f
    };
    /////////////////////////

    GLuint VBOS[2], VAOS[2];
    glGenVertexArrays(2, VAOS); // Generate multiple VAO and VBO at the same time
    glGenBuffers(2, VBOS);
    // ==============
    // FIRST TRIANGLE
    // ==============
    // Bind the Vertex Array Object first, then bind and set vertex buffer(s) and attribute pointer(s).
    glBindVertexArray(VAOS[0]);
    glBindBuffer(GL_ARRAY_BUFFER, VBOS[0]);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices1), vertices1, GL_STATIC_DRAW);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0);
    glEnableVertexAttribArray(0);
    glBindVertexArray(0); // Unbind VAO (it's always a good thing to unbind any buffer/array to prevent strange bugs), remember: do NOT unbind the EBO, keep it bound to this VAO
    // ===============
    // SECOND TRIANGLE
    // ===============
    // Bind the Vertex Array Object first, then bind and set vertex buffer(s) and attribute pointer(s).
    glBindVertexArray(VAOS[1]);
    glBindBuffer(GL_ARRAY_BUFFER, VBOS[1]);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices2), vertices2, GL_STATIC_DRAW);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0);
    glEnableVertexAttribArray(0);
    glBindVertexArray(0); // Unbind VAO (it's always a good thing to unbind any buffer/array to prevent strange bugs), remember: do NOT unbind the EBO, keep it bound to this VAO

    //glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);

    // Game loop
    while (!glfwWindowShouldClose(window))
    {
        // Check if any events have been activiated (key pressed, mouse moved etc.) and call corresponding response functions
        glfwPollEvents();

        // Render
        // Clear the colorbuffer
        glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);

        // Draw first rectangle
        // Activate shader
        glUseProgram(shaderProgram1);
        glBindVertexArray(VAOS[0]);
        glDrawArrays(GL_TRIANGLES, 0, 3); // The last number indicates the number of vertices we're drawing.
        // Draw second rectangle
        // Activate shader
        glUseProgram(shaderProgram2);
        glBindVertexArray(VAOS[1]);
        glDrawArrays(GL_TRIANGLES, 0, 3); // The last number indicates the number of vertices we're drawing.
        glBindVertexArray(0);

        // Swap the screen buffers
        glfwSwapBuffers(window);
    }

    // Properly de-allocate all resources once they've outlived their purpose
    glDeleteVertexArrays(2, VAOS);
    glDeleteBuffers(2, VBOS);

    // Terminate GLFW, clearing any resources allocated by GLFW.
    glfwTerminate();
    return 0;
}
void* GLESHardwareIndexBuffer::lockImpl(size_t offset,
                                        size_t length,
                                        LockOptions options)
{
    if(mIsLocked)
    {
        OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR,
                    "Invalid attempt to lock an index buffer that has already been locked",
                    "GLESHardwareIndexBuffer::lock");
    }

    void* retPtr = 0;
    GLenum access = 0;
    GLESHardwareBufferManager* glBufManager = static_cast<GLESHardwareBufferManager*>(HardwareBufferManager::getSingletonPtr());

    if(length < glBufManager->getGLMapBufferThreshold())
    {
        retPtr = glBufManager->allocateScratch((uint32)length);
        if (retPtr)
        {
            mLockedToScratch = true;
            mScratchOffset = offset;
            mScratchSize = length;
            mScratchPtr = retPtr;
            mScratchUploadOnUnlock = (options != HBL_READ_ONLY);

            if (options != HBL_DISCARD)
            {
                readData(offset, length, retPtr);
            }
        }
    }
    else
    {
        OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR,
                    "Invalid Buffer lockSize",
                    "GLESHardwareIndexBuffer::lock");
    }

#if GL_OES_mapbuffer
    if (!retPtr)
    {
        glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, mBufferId );
        // Use glMapBuffer
        if(options == HBL_DISCARD)
        {
            // Discard the buffer
            glBufferData(GL_ELEMENT_ARRAY_BUFFER, mSizeInBytes, NULL,
                         GLESHardwareBufferManager::getGLUsage(mUsage));
        }
        if (mUsage & HBU_WRITE_ONLY)
            access = GL_WRITE_ONLY_OES;

        void* pBuffer = glMapBufferOES( GL_ELEMENT_ARRAY_BUFFER, access );

        if(pBuffer == 0)
        {
            OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR,
                        "Index Buffer: Out of memory",
                        "GLESHardwareIndexBuffer::lock");
        }

        // return offsetted
        retPtr = static_cast<void*>(static_cast<unsigned char*>(pBuffer) + offset);

        mLockedToScratch = false;
    }
    mIsLocked = true;
#endif

    return retPtr;
}
// This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
// If text or lines are blurry when integrating ImGui in your engine:
// - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
void ImGui_ImplGlut_RenderDrawLists(ImDrawData* draw_data)
{
    // Backup GL state
    GLint last_program; glGetIntegerv(GL_CURRENT_PROGRAM, &last_program);
    GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
    GLint last_array_buffer; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer);
    GLint last_element_array_buffer; glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &last_element_array_buffer);
    GLint last_vertex_array; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array);
    GLint last_blend_src; glGetIntegerv(GL_BLEND_SRC, &last_blend_src);
    GLint last_blend_dst; glGetIntegerv(GL_BLEND_DST, &last_blend_dst);
    GLint last_blend_equation_rgb; glGetIntegerv(GL_BLEND_EQUATION_RGB, &last_blend_equation_rgb);
    GLint last_blend_equation_alpha; glGetIntegerv(GL_BLEND_EQUATION_ALPHA, &last_blend_equation_alpha);
    GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport);
    GLboolean last_enable_blend = glIsEnabled(GL_BLEND);
    GLboolean last_enable_cull_face = glIsEnabled(GL_CULL_FACE);
    GLboolean last_enable_depth_test = glIsEnabled(GL_DEPTH_TEST);
    GLboolean last_enable_scissor_test = glIsEnabled(GL_SCISSOR_TEST);

    // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
    glEnable(GL_BLEND);
    glBlendEquation(GL_FUNC_ADD);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glDisable(GL_CULL_FACE);
    glDisable(GL_DEPTH_TEST);
    glEnable(GL_SCISSOR_TEST);
    glActiveTexture(GL_TEXTURE0);

    // Handle cases of screen coordinates != from framebuffer coordinates (e.g. retina displays)
    ImGuiIO& io = ImGui::GetIO();
    int fb_width = (int)(io.DisplaySize.x * io.DisplayFramebufferScale.x);
    int fb_height = (int)(io.DisplaySize.y * io.DisplayFramebufferScale.y);
    draw_data->ScaleClipRects(io.DisplayFramebufferScale);

    // Setup viewport, orthographic projection matrix
    glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height);
    const float ortho_projection[4][4] =
    {
        { 2.0f/io.DisplaySize.x, 0.0f,                   0.0f, 0.0f },
        { 0.0f,                  2.0f/-io.DisplaySize.y, 0.0f, 0.0f },
        { 0.0f,                  0.0f,                  -1.0f, 0.0f },
        {-1.0f,                  1.0f,                   0.0f, 1.0f },
    };
    glUseProgram(g_ShaderHandle);
    glUniform1i(g_AttribLocationTex, 0);
    glUniformMatrix4fv(g_AttribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]);
    glBindVertexArray(g_VaoHandle);

    for (int n = 0; n < draw_data->CmdListsCount; n++)
    {
        const ImDrawList* cmd_list = draw_data->CmdLists[n];
        const ImDrawIdx* idx_buffer_offset = 0;

        glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle);
        glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)cmd_list->VtxBuffer.size() * sizeof(ImDrawVert), (GLvoid*)&cmd_list->VtxBuffer.front(), GL_STREAM_DRAW);

        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_ElementsHandle);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, (GLsizeiptr)cmd_list->IdxBuffer.size() * sizeof(ImDrawIdx), (GLvoid*)&cmd_list->IdxBuffer.front(), GL_STREAM_DRAW);

        for (const ImDrawCmd* pcmd = cmd_list->CmdBuffer.begin(); pcmd != cmd_list->CmdBuffer.end(); pcmd++)
        {
            if (pcmd->UserCallback)
            {
                pcmd->UserCallback(cmd_list, pcmd);
            }
            else
            {
                glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId);
                glScissor((int)pcmd->ClipRect.x, (int)(fb_height - pcmd->ClipRect.w), (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y));
                glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset);
            }
            idx_buffer_offset += pcmd->ElemCount;
        }
    }

    // Restore modified GL state
    glUseProgram(last_program);
    glBindTexture(GL_TEXTURE_2D, last_texture);
    glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, last_element_array_buffer);
    glBindVertexArray(last_vertex_array);
    glBlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha);
    glBlendFunc(last_blend_src, last_blend_dst);
    if (last_enable_blend) glEnable(GL_BLEND); else glDisable(GL_BLEND);
    if (last_enable_cull_face) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE);
    if (last_enable_depth_test) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST);
    if (last_enable_scissor_test) glEnable(GL_SCISSOR_TEST); else glDisable(GL_SCISSOR_TEST);
    glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]);
}
static MeshPod CreateCylinder()
{
    const int VertexCount = (Slices+1) * (Stacks+1);
    const int FillIndexCount = (Slices+1) * Stacks * 6;

    const int circles = (Stacks+1)*Slices;
    const int longitudinal = Stacks*Slices;
    const int LineIndexCount = 2 * (circles + longitudinal);
 
    // Create a buffer with positions
    GLuint positionsVbo;
    if (1) {
        Point3 verts[VertexCount];
        Point3* pVert = &verts[0];
        float ds = 1.0f / Stacks;
        float dt = 1.0f / Slices;

        // The upper bounds in these loops are tweaked to reduce the
        // chance of precision error causing an incorrect # of iterations.
        for (float s = 0; s < 1 + ds / 2; s += ds) {
            for (float t = 0; t < 1 + dt / 2; t += dt) {
                *pVert++ = EvaluateCylinder(s, t);
            }
        }

        pezCheck(pVert - &verts[0] == VertexCount, "Tessellation error.");

        GLsizeiptr size = sizeof(verts);
        const GLvoid* data = &verts[0].x;
        GLenum usage = GL_STATIC_DRAW;
        glGenBuffers(1, &positionsVbo);
        glBindBuffer(GL_ARRAY_BUFFER, positionsVbo);
        glBufferData(GL_ARRAY_BUFFER, size, data, usage);
    }

    // Create a buffer of 16-bit triangle indices
    GLuint trianglesVbo;
    if (1) {
        GLushort inds[FillIndexCount];
        GLushort* pIndex = &inds[0];
        GLushort n = 0;
        for (GLushort j = 0; j < Stacks; j++) {
            int vps = Slices+1; // vertices per stack
            for (GLushort i = 0; i < vps; i++) {
                *pIndex++ = (n + i + vps);
                *pIndex++ = n + (i + 1) % vps;
                *pIndex++ = n + i;
                
                *pIndex++ = (n + (i + 1) % vps + vps);
                *pIndex++ = (n + (i + 1) % vps);
                *pIndex++ = (n + i + vps);
            }
            n += vps;
        }

        pezCheck(pIndex - &inds[0] == FillIndexCount, "Tessellation error.");

        GLsizeiptr size = sizeof(inds);
        const GLvoid* data = &inds[0];
        GLenum usage = GL_STATIC_DRAW;
        glGenBuffers(1, &trianglesVbo);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, trianglesVbo);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, size, data, usage);
    }

    // Create a buffer of 16-bit line indices
    GLuint lineVbo;
    if (1) {

        GLushort inds[LineIndexCount];
        GLushort* pIndex = &inds[0];

        // Circles:
        GLushort n = 0;
        for (GLushort j = 0; j < Stacks+1; j++) {
            for (GLushort i = 0; i < Slices; i++) {
                *pIndex++ = n + i;
                *pIndex++ = n + i + 1;
            }
            n += Slices + 1;
        }

        // Longitudinal:
        n = 0;
        for (GLushort j = 0; j < Stacks; j++) {
            for (GLushort i = 0; i < Slices; i++) {
                *pIndex++ = n + i;
                *pIndex++ = n + i + (Slices + 1);
            }
            n += Slices + 1;
        }

        pezCheck(pIndex - &inds[0] == LineIndexCount, "Tessellation error.");

        GLsizeiptr size = sizeof(inds);
        const GLvoid* data = &inds[0];
        GLenum usage = GL_STATIC_DRAW;
        glGenBuffers(1, &lineVbo);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, lineVbo);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, size, data, usage);
    }

    MeshPod mesh;
    mesh.VertexCount = VertexCount;
    mesh.FillIndexCount = FillIndexCount;
    mesh.LineIndexCount = LineIndexCount;

    glGenVertexArrays(1, &mesh.FillVao);
    glBindVertexArray(mesh.FillVao);
    glBindBuffer(GL_ARRAY_BUFFER, positionsVbo);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, trianglesVbo);
    glVertexAttribPointer(Attr.Position, 3, GL_FLOAT, GL_FALSE, 12, 0);
    glEnableVertexAttribArray(Attr.Position);

    glGenVertexArrays(1, &mesh.LineVao);
    glBindVertexArray(mesh.LineVao);
    glBindBuffer(GL_ARRAY_BUFFER, positionsVbo);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, lineVbo);
    glVertexAttribPointer(Attr.Position, 3, GL_FLOAT, GL_FALSE, 12, 0);
    glEnableVertexAttribArray(Attr.Position);

    return mesh;
}
void vbo_buffer_data(void *data, size_t data_sizeof)
{
   glBufferData(GL_ARRAY_BUFFER, data_sizeof, data, GL_DYNAMIC_DRAW);
}
Beispiel #18
0
bool initialize(char *objectFile)
{
    // Initialize basic geometry and shaders for this example

    //this defines a cube, this is why a model loader is nice
    //you can also do this with a draw elements and indices, try to get that working
    
    Vertex *geometry = loadOBJ( objectFile, geoSize );

    // Create a Vertex Buffer object to store this vertex info on the GPU
    glGenBuffers(1, &vbo_geometry);
    glBindBuffer(GL_ARRAY_BUFFER, vbo_geometry);
    glBufferData(GL_ARRAY_BUFFER, geoSize, geometry, GL_STATIC_DRAW);
std::cout << geoSize;
    //--Geometry done

    GLuint vertex_shader = glCreateShader(GL_VERTEX_SHADER);
    GLuint fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);

    //Shader Sources
    char vertexFile[] = "../src/shaders/default.vert";
    char fragmentFile[] = "../src/shaders/default.frag";

    const char *vs = readFile(vertexFile);
    const char *fs = readFile(fragmentFile);


    //compile the shaders
    GLint shader_status;

    // Vertex shader first
    glShaderSource(vertex_shader, 1, &vs, NULL);
    glCompileShader(vertex_shader);
    //check the compile status
    glGetShaderiv(vertex_shader, GL_COMPILE_STATUS, &shader_status);
    if(!shader_status)
    {
        std::cerr << "[F] FAILED TO COMPILE VERTEX SHADER!" << std::endl;
        return false;
    }

    // Now the Fragment shader
    glShaderSource(fragment_shader, 1, &fs, NULL);
    glCompileShader(fragment_shader);
    //check the compile status
    glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &shader_status);
    if(!shader_status)
    {
        std::cerr << "[F] FAILED TO COMPILE FRAGMENT SHADER!" << std::endl;
        return false;
    }

    //Now we link the 2 shader objects into a program
    //This program is what is run on the GPU
    program = glCreateProgram();
    glAttachShader(program, vertex_shader);
    glAttachShader(program, fragment_shader);
    glLinkProgram(program);
    //check if everything linked ok
    glGetProgramiv(program, GL_LINK_STATUS, &shader_status);
    if(!shader_status)
    {
        std::cerr << "[F] THE SHADER PROGRAM FAILED TO LINK" << std::endl;
        return false;
    }

    //Now we set the locations of the attributes and uniforms
    //this allows us to access them easily while rendering
    loc_position = glGetAttribLocation(program,
                    const_cast<const char*>("v_position"));
    if(loc_position == -1)
    {
        std::cerr << "[F] POSITION NOT FOUND" << std::endl;
        return false;
    }

    loc_color = glGetAttribLocation(program,
                    const_cast<const char*>("v_color"));
    if(loc_color == -1)
    {
        std::cerr << "[F] V_COLOR NOT FOUND" << std::endl;
        return false;
    }

    loc_mvpmat = glGetUniformLocation(program,
                    const_cast<const char*>("mvpMatrix"));
    if(loc_mvpmat == -1)
    {
        std::cerr << "[F] MVPMATRIX NOT FOUND" << std::endl;
        return false;
    }
    
    //--Init the view and projection matrices
    //  if you will be having a moving camera the view matrix will need to more dynamic
    //  ...Like you should update it before you render more dynamic 
    //  for this project having them static will be fine
    view = glm::lookAt( glm::vec3(0.0, 8.0, -16.0), //Eye Position
                        glm::vec3(0.0, 0.0, 0.0), //Focus point
                        glm::vec3(0.0, 1.0, 0.0)); //Positive Y is up

    projection = glm::perspective( 45.0f, //the FoV typically 90 degrees is good which is what this is set to
                                   float(w)/float(h), //Aspect Ratio, so Circles stay Circular
                                   0.01f, //Distance to the near plane, normally a small value like this
                                   100.0f); //Distance to the far plane, 

    //enable depth testing
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LESS);

    //and its done
    return true;
}
void setupBuffers()
{
	glGenVertexArrays(3, vao);
	//
	// VAO for 1st triangle
	//
	glBindVertexArray(vao[0]);
	// Generate two slots for the vertex and color buffers

	glGenBuffers(2, buffers);
	// bind buffer for vertices and copy data into buffer
	glBindBuffer(GL_ARRAY_BUFFER, buffers[0]);
	glBufferData(GL_ARRAY_BUFFER, sizeof(vertices1), vertices1, GL_STREAM_DRAW);
	glEnableVertexAttribArray(vertexLoc);
	glVertexAttribPointer(vertexLoc, 4, GL_FLOAT, 0, 0, 0);

	// bind buffer for colors and copy data into buffer
	glBindBuffer(GL_ARRAY_BUFFER, buffers[1]);
	glBufferData(GL_ARRAY_BUFFER, sizeof(colors1), colors1, GL_STREAM_DRAW);
	glEnableVertexAttribArray(colorLoc);
	glVertexAttribPointer(colorLoc, 4, GL_FLOAT, 0, 0, 0); 

	//
	// VAO for second triangle
	//
	glBindVertexArray(vao[1]);
	// Generate two slots for the vertex and color buffers
	glGenBuffers(2, buffers);

	// bind buffer for vertices and copy data into buffer
	glBindBuffer(GL_ARRAY_BUFFER, buffers[0]);
	glBufferData(GL_ARRAY_BUFFER, sizeof(vertices2), vertices2, GL_STREAM_DRAW);
	glEnableVertexAttribArray(vertexLoc);
	glVertexAttribPointer(vertexLoc, 4, GL_FLOAT, 0, 0, 0);

	// bind buffer for colors and copy data into buffer
	glBindBuffer(GL_ARRAY_BUFFER, buffers[1]);
	glBufferData(GL_ARRAY_BUFFER, sizeof(colors2), colors2, GL_STREAM_DRAW);
	glEnableVertexAttribArray(colorLoc);
	glVertexAttribPointer(colorLoc, 4, GL_FLOAT, 0, 0, 0);

	//
	// VAO for 3rd triangle
	//
	glBindVertexArray(vao[2]);
	// Generate two slots for the vertex and color buffers
	glGenBuffers(2, buffers);

	// bind buffer for vertices and copy data into buffer
	glBindBuffer(GL_ARRAY_BUFFER, buffers[0]);
	glBufferData(GL_ARRAY_BUFFER, sizeof(vertices3), vertices3, GL_STREAM_DRAW);
	glEnableVertexAttribArray(vertexLoc);
	glVertexAttribPointer(vertexLoc, 4, GL_FLOAT, 0, 0, 0);

	// bind buffer for colors and copy data into buffer
	glBindBuffer(GL_ARRAY_BUFFER, buffers[1]);
	glBufferData(GL_ARRAY_BUFFER, sizeof(colors3), colors3, GL_STREAM_DRAW);
	glEnableVertexAttribArray(colorLoc);
	glVertexAttribPointer(colorLoc, 4, GL_FLOAT, 0, 0, 0);

	// Transform feedback buffer
	glGenBuffers(3, tfbuf);
	glBindBuffer(GL_TRANSFORM_FEEDBACK_BUFFER, tfbuf[0]);
	glBufferData(GL_TRANSFORM_FEEDBACK_BUFFER, 3 * sizeof(vertices1) + 3 * sizeof(colors1), NULL, GL_STREAM_DRAW);

	glBindBuffer(GL_TRANSFORM_FEEDBACK_BUFFER, tfbuf[1]);
	glBufferData(GL_TRANSFORM_FEEDBACK_BUFFER, 3 * sizeof(vertices1) + 3 * sizeof(colors1), NULL, GL_STREAM_DRAW);

	glBindBuffer(GL_TRANSFORM_FEEDBACK_BUFFER, tfbuf[2]);
	glBufferData(GL_TRANSFORM_FEEDBACK_BUFFER, 3 * sizeof(vertices1) + 3 * sizeof(colors1), NULL, GL_STREAM_DRAW);

}
void
VSShaderLib::addBlocks() {

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

	UniformBlock block;

	glGetProgramiv(pProgram, GL_ACTIVE_UNIFORM_BLOCKS, &count);

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

		if (!spBlocks.count(name)) {
			// Get buffers size
			block = spBlocks[name];
			glGetActiveUniformBlockiv(pProgram, i, GL_UNIFORM_BLOCK_DATA_SIZE, &dataSize);
			//printf("DataSize:%d\n", dataSize);
			glGenBuffers(1, &block.buffer);
			glBindBuffer(GL_UNIFORM_BUFFER, block.buffer);
			glBufferData(GL_UNIFORM_BUFFER, dataSize, NULL, GL_DYNAMIC_DRAW);
			glUniformBlockBinding(pProgram, i, spBlockCount);
			glBindBufferRange(GL_UNIFORM_BUFFER, spBlockCount, block.buffer, 0, dataSize);

			glGetActiveUniformBlockiv(pProgram, i, GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS, &activeUnif);

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

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

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

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

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

				block.uniformOffsets[name2] = bUni;


			}
			free(name2);

			block.size = dataSize;
			block.bindingIndex = spBlockCount;
			spBlocks[name] = block;
			spBlockCount++;
		}
		else
			glUniformBlockBinding(pProgram, i, spBlocks[name].bindingIndex);

	}

}
// The MAIN function, from here we start the application and run the game loop
int main()
{
    // Init GLFW
    glfwInit();
    // Set all the required options for GLFW
    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);
    
    // On mac os, must have this config.
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    
    // Create a GLFWwindow object that we can use for GLFW's functions
    GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr);
    glfwMakeContextCurrent(window);
    
    // Set the required callback functions
    glfwSetKeyCallback(window, key_callback);
    
    // Set this to true so GLEW knows to use a modern approach to retrieving function pointers and extensions
    glewExperimental = GL_TRUE;
    // Initialize GLEW to setup the OpenGL Function pointers
    glewInit();
    
    // Define the viewport dimensions
    glViewport(0, 0, WIDTH, HEIGHT);
    
    glEnable(GL_DEPTH_TEST);
    
    
    // Build and compile our shader program
    ShaderProgram ourShader("/Users/Evan/Documents/XcodeWorkspace/OpenGLCoreStudy/OpenGLCoreStudy/TestCode/GLSL/First3DObjects.vsh", "/Users/Evan/Documents/XcodeWorkspace/OpenGLCoreStudy/OpenGLCoreStudy/TestCode/GLSL/First3DObjects.fsh");
    
    
    // Set up vertex data (and buffer(s)) and attribute pointers
    GLfloat vertices[] = {
        -0.5f, -0.5f, -0.5f,  0.0f, 0.0f,
        0.5f, -0.5f, -0.5f,  1.0f, 0.0f,
        0.5f,  0.5f, -0.5f,  1.0f, 1.0f,
        0.5f,  0.5f, -0.5f,  1.0f, 1.0f,
        -0.5f,  0.5f, -0.5f,  0.0f, 1.0f,
        -0.5f, -0.5f, -0.5f,  0.0f, 0.0f,
        
        -0.5f, -0.5f,  0.5f,  0.0f, 0.0f,
        0.5f, -0.5f,  0.5f,  1.0f, 0.0f,
        0.5f,  0.5f,  0.5f,  1.0f, 1.0f,
        0.5f,  0.5f,  0.5f,  1.0f, 1.0f,
        -0.5f,  0.5f,  0.5f,  0.0f, 1.0f,
        -0.5f, -0.5f,  0.5f,  0.0f, 0.0f,
        
        -0.5f,  0.5f,  0.5f,  1.0f, 0.0f,
        -0.5f,  0.5f, -0.5f,  1.0f, 1.0f,
        -0.5f, -0.5f, -0.5f,  0.0f, 1.0f,
        -0.5f, -0.5f, -0.5f,  0.0f, 1.0f,
        -0.5f, -0.5f,  0.5f,  0.0f, 0.0f,
        -0.5f,  0.5f,  0.5f,  1.0f, 0.0f,
        
        0.5f,  0.5f,  0.5f,  1.0f, 0.0f,
        0.5f,  0.5f, -0.5f,  1.0f, 1.0f,
        0.5f, -0.5f, -0.5f,  0.0f, 1.0f,
        0.5f, -0.5f, -0.5f,  0.0f, 1.0f,
        0.5f, -0.5f,  0.5f,  0.0f, 0.0f,
        0.5f,  0.5f,  0.5f,  1.0f, 0.0f,
        
        -0.5f, -0.5f, -0.5f,  0.0f, 1.0f,
        0.5f, -0.5f, -0.5f,  1.0f, 1.0f,
        0.5f, -0.5f,  0.5f,  1.0f, 0.0f,
        0.5f, -0.5f,  0.5f,  1.0f, 0.0f,
        -0.5f, -0.5f,  0.5f,  0.0f, 0.0f,
        -0.5f, -0.5f, -0.5f,  0.0f, 1.0f,
        
        -0.5f,  0.5f, -0.5f,  0.0f, 1.0f,
        0.5f,  0.5f, -0.5f,  1.0f, 1.0f,
        0.5f,  0.5f,  0.5f,  1.0f, 0.0f,
        0.5f,  0.5f,  0.5f,  1.0f, 0.0f,
        -0.5f,  0.5f,  0.5f,  0.0f, 0.0f,
        -0.5f,  0.5f, -0.5f,  0.0f, 1.0f
    };
    glm::vec3 cubePositions[] = {
        glm::vec3( 0.0f,  0.0f,  0.0f),
        glm::vec3( 2.0f,  5.0f, -15.0f),
        glm::vec3(-1.5f, -2.2f, -2.5f),
        glm::vec3(-3.8f, -2.0f, -12.3f),
        glm::vec3( 2.4f, -0.4f, -3.5f),
        glm::vec3(-1.7f,  3.0f, -7.5f),
        glm::vec3( 1.3f, -2.0f, -2.5f),
        glm::vec3( 1.5f,  2.0f, -2.5f),
        glm::vec3( 1.5f,  0.2f, -1.5f),
        glm::vec3(-1.3f,  1.0f, -1.5f)
    };
    GLuint VBO, VAO;
    glGenVertexArrays(1, &VAO);
    glGenBuffers(1, &VBO);
    
    glBindVertexArray(VAO);
    
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
    
    // Position attribute
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)0);
    glEnableVertexAttribArray(0);
    // TexCoord attribute
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
    glEnableVertexAttribArray(2);
    
    glBindVertexArray(0); // Unbind VAO
    
    
    // Load and create a texture
    GLuint texture1;
    GLuint texture2;
    // ====================
    // Texture 1
    // ====================
    glGenTextures(1, &texture1);
    glBindTexture(GL_TEXTURE_2D, texture1); // All upcoming GL_TEXTURE_2D operations now have effect on our texture object
    // Set our texture parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);	// Set texture wrapping to GL_REPEAT
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    // Set texture filtering
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    // Load, create texture and generate mipmaps
    int width, height;
    unsigned char* image = SOIL_load_image("/Users/Evan/Documents/XcodeWorkspace/OpenGLCoreStudy/OpenGLCoreStudy/Resource/Image/container.jpg", &width, &height, 0, SOIL_LOAD_RGB);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
    glGenerateMipmap(GL_TEXTURE_2D);
    SOIL_free_image_data(image);
    glBindTexture(GL_TEXTURE_2D, 0); // Unbind texture when done, so we won't accidentily mess up our texture.
    // ===================
    // Texture 2
    // ===================
    glGenTextures(1, &texture2);
    glBindTexture(GL_TEXTURE_2D, texture2);
    // Set our texture parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    // Set texture filtering
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    // Load, create texture and generate mipmaps
    image = SOIL_load_image("/Users/Evan/Documents/XcodeWorkspace/OpenGLCoreStudy/OpenGLCoreStudy/Resource/Image/awesomeface.png", &width, &height, 0, SOIL_LOAD_RGB);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
    glGenerateMipmap(GL_TEXTURE_2D);
    SOIL_free_image_data(image);
    glBindTexture(GL_TEXTURE_2D, 0);
    
    
    // Game loop
    while (!glfwWindowShouldClose(window))
    {
        GLfloat currentFrame = glfwGetTime();
        deltaTime = currentFrame - lastFrame;
        lastFrame = currentFrame;
        
        // Check if any events have been activiated (key pressed, mouse moved etc.) and call corresponding response functions
        glfwPollEvents();
        
        do_movement();
        
        // Render
        // Clear the colorbuffer
        glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        
        
        // Bind Textures using texture units
        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, texture1);
        glUniform1i(glGetUniformLocation(ourShader.program, "ourTexture1"), 0);
        glActiveTexture(GL_TEXTURE1);
        glBindTexture(GL_TEXTURE_2D, texture2);
        glUniform1i(glGetUniformLocation(ourShader.program, "ourTexture2"), 1);
        
        // Activate shader
        ourShader.useShader();
        
        // Camera/View transformation
        glm::mat4 view;
        view = glm::lookAt(cameraPos, cameraPos + cameraFront, cameraUp);
        // Projection
        glm::mat4 projection;
        projection = glm::perspective(45.0f, (GLfloat)WIDTH / (GLfloat)HEIGHT, 0.1f, 100.0f);
        // Get the uniform locations
        GLint modelLoc = glGetUniformLocation(ourShader.program, "model");
        GLint viewLoc = glGetUniformLocation(ourShader.program, "view");
        GLint projLoc = glGetUniformLocation(ourShader.program, "projection");
        // Pass the matrices to the shader
        glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));
        glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projection));
        
        glBindVertexArray(VAO);
        for (GLuint i = 0; i < 10; i++)
        {
            // Calculate the model matrix for each object and pass it to shader before drawing
            glm::mat4 model;
            model = glm::translate(model, cubePositions[i]);
            GLfloat angle = 20.0f * i;
            model = glm::rotate(model, angle, glm::vec3(1.0f, 0.3f, 0.5f));
            glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
            
            glDrawArrays(GL_TRIANGLES, 0, 36);
        }
        glBindVertexArray(0);
        
        // Swap the screen buffers
        glfwSwapBuffers(window);
    }
    // Properly de-allocate all resources once they've outlived their purpose
    glDeleteVertexArrays(1, &VAO);
    glDeleteBuffers(1, &VBO);
    // Terminate GLFW, clearing any resources allocated by GLFW.
    glfwTerminate();
    return 0;
}
void
piglit_init(int argc, char **argv)
{
	static const GLuint indices[] = { 0, 1, 2, 3 };
	static const GLfloat verts[] = {
		/* These vertices should never be accessed due to the way
		 * glDrawElementsBaseVertex is called.
		 */
		-1.0, -1.0,
		 1.0, -1.0,
		 1.0,  1.0,
		-1.0,  1.0,

		-1.0, -1.0,
		 0.0, -1.0,
		 0.0,  0.0,
		-1.0,  0.0,

		 0.0, -1.0,
		 1.0, -1.0,
		 1.0,  0.0,
		 0.0,  0.0,

		-1.0,  0.0,
		 0.0,  0.0,
		 0.0,  1.0,
		-1.0,  1.0,

		 0.0,  0.0,
		 1.0,  0.0,
		 1.0,  1.0,
		 0.0,  1.0,
	};

	GLuint prog = piglit_build_simple_program(
		"#version 140\n"
		"\n"
		"in vec4 piglit_vertex;\n"
		"out vec3 c;\n"
		"\n"
		"const vec3 colors[] = vec3[](\n"
		"	vec3(1, 0, 0),\n"
		"	vec3(1, 0, 0),\n"
		"	vec3(1, 0, 0),\n"
		"	vec3(1, 0, 0),\n"
		"\n"
		"	vec3(0, 1, 0),\n"
		"	vec3(0, 1, 0),\n"
		"	vec3(0, 1, 0),\n"
		"	vec3(0, 1, 0),\n"
		"\n"
		"	vec3(0, 0, 1),\n"
		"	vec3(0, 0, 1),\n"
		"	vec3(0, 0, 1),\n"
		"	vec3(0, 0, 1),\n"
		"\n"
		"	vec3(1, 1, 0),\n"
		"	vec3(1, 1, 0),\n"
		"	vec3(1, 1, 0),\n"
		"	vec3(1, 1, 0),\n"
		"\n"
		"	vec3(1, 0, 1),\n"
		"	vec3(1, 0, 1),\n"
		"	vec3(1, 0, 1),\n"
		"	vec3(1, 0, 1)\n"
		");\n"
		"void main() {\n"
		"       c = colors[gl_VertexID];\n"
		"	gl_Position = piglit_vertex;\n"
		"}\n",

		"#version 140\n"
		"in vec3 c;\n"
		"out vec4 fragcolor;\n"
		"\n"
		"void main() {\n"
		"	fragcolor = vec4(c, 1);\n"
		"}\n");

	GLuint vao;
	GLuint buf[2];

	glUseProgram(prog);

	glGenVertexArrays(1, &vao);
	glBindVertexArray(vao);

	glGenBuffers(2, buf);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buf[0]);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices,
		     GL_STATIC_DRAW);

	glBindBuffer(GL_ARRAY_BUFFER, buf[1]);
	glBufferData(GL_ARRAY_BUFFER, sizeof(verts), verts,
		     GL_STATIC_DRAW);

	glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, (void *) 0);
	glEnableVertexAttribArray(0);
}
bool
OsdGLDrawContext::allocate(FarMesh<OsdVertex> *farMesh,
                           GLuint vbo,
                           int numElements,
                           bool requirePtexCoordinates,
                           bool requireFVarData)
{
    FarPatchTables const * patchTables = farMesh->GetPatchTables();

    if (not patchTables) {
        // uniform patches
        isAdaptive = false;

        // XXX: farmesh should have FarDensePatchTable for dense mesh indices.
        //      instead of GetFaceVertices().
        const FarSubdivisionTables<OsdVertex> *tables = farMesh->GetSubdivisionTables();
        int level = tables->GetMaxLevel();
        const std::vector<int> &indices = farMesh->GetFaceVertices(level-1);

        // XXX: farmesh or FarSubdivisionTables should have a virtual method
        // to determine loop or not
        bool loop =
            dynamic_cast<const FarLoopSubdivisionTables<OsdVertex>*>(tables) != NULL;

        int numIndices = (int)indices.size();

        // Allocate and fill index buffer.
        glGenBuffers(1, &patchIndexBuffer);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, patchIndexBuffer);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER,
                     numIndices * sizeof(unsigned int), &(indices[0]), GL_STATIC_DRAW);

#if defined(GL_ES_VERSION_2_0)
        // OpenGLES 2 supports only triangle topologies for filled
        // primitives i.e. not QUADS or PATCHES or LINES_ADJACENCY
        // For the convenience of clients build build a triangles
        // index buffer by splitting quads.
        int numQuads = indices.size() / 4;
        int numTrisIndices = numQuads * 6;

        std::vector<short> trisIndices;
        trisIndices.reserve(numTrisIndices);
        for (int i=0; i<numQuads; ++i) {
            const int * quad = &indices[i*4];
            trisIndices.push_back(short(quad[0]));
            trisIndices.push_back(short(quad[1]));
            trisIndices.push_back(short(quad[2]));

            trisIndices.push_back(short(quad[2]));
            trisIndices.push_back(short(quad[3]));
            trisIndices.push_back(short(quad[0]));
        }

        // Allocate and fill triangles index buffer.
        glGenBuffers(1, &patchTrianglesIndexBuffer);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, patchTrianglesIndexBuffer);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER,
                     numTrisIndices * sizeof(short), &(trisIndices[0]), GL_STATIC_DRAW);
#endif

        OsdPatchArray array;
        array.desc.type = kNonPatch;
        array.patchSize = loop ? 3 : 4;
        array.firstIndex = 0;
        array.numIndices = numIndices;

        patchArrays.push_back(array);

        // Allocate ptex coordinate buffer if requested (for non-adaptive)
        if (requirePtexCoordinates) {
#if defined(GL_ARB_texture_buffer_object) || defined(GL_VERSION_3_1)
            GLuint ptexCoordinateBuffer = 0;
            glGenTextures(1, &ptexCoordinateTextureBuffer);
            glGenBuffers(1, &ptexCoordinateBuffer);
            glBindBuffer(GL_TEXTURE_BUFFER, ptexCoordinateBuffer);

            const std::vector<int> &ptexCoordinates =
                farMesh->GetPtexCoordinates(level-1);
            int size = (int)ptexCoordinates.size() * sizeof(GLint);

            glBufferData(GL_TEXTURE_BUFFER, size, &(ptexCoordinates[0]), GL_STATIC_DRAW);

            glBindTexture(GL_TEXTURE_BUFFER, ptexCoordinateTextureBuffer);
            glTexBuffer(GL_TEXTURE_BUFFER, GL_RG32I, ptexCoordinateBuffer);
            glDeleteBuffers(1, &ptexCoordinateBuffer);
            glBindTexture(GL_TEXTURE_BUFFER, 0);
#endif
        }

        // Allocate fvar data buffer if requested (for non-adaptive)
        if (requireFVarData) {
#if defined(GL_ARB_texture_buffer_object) || defined(GL_VERSION_3_1)
            GLuint fvarDataBuffer = 0;
            glGenTextures(1, &fvarDataTextureBuffer);
            glGenBuffers(1, &fvarDataBuffer);
            glBindBuffer(GL_TEXTURE_BUFFER, fvarDataBuffer);

            const std::vector<float> &fvarData = farMesh->GetFVarData(level-1);
            int size = (int)fvarData.size() * sizeof(float);

            glBufferData(GL_TEXTURE_BUFFER, size, &(fvarData[0]), GL_STATIC_DRAW);

            glBindTexture(GL_TEXTURE_BUFFER, fvarDataTextureBuffer);
            glTexBuffer(GL_TEXTURE_BUFFER, GL_R32F, fvarDataBuffer);
            glDeleteBuffers(1, &fvarDataBuffer);
            glBindTexture(GL_TEXTURE_BUFFER, 0);
#endif
        }

        return true;
    }

    // adaptive patches
    isAdaptive = true;

    // Determine buffer sizes
    int totalPatchIndices = 
        patchTables->GetFullRegularPatches().GetSize() +
        patchTables->GetFullBoundaryPatches().GetSize() +
        patchTables->GetFullCornerPatches().GetSize() +
        patchTables->GetFullGregoryPatches().GetSize() +
        patchTables->GetFullBoundaryGregoryPatches().GetSize();

    int totalPatchLevels = 
        patchTables->GetFullRegularPatches().GetSize()/patchTables->GetRegularPatchRingsize() +
        patchTables->GetFullBoundaryPatches().GetSize()/patchTables->GetBoundaryPatchRingsize() +
        patchTables->GetFullCornerPatches().GetSize()/patchTables->GetCornerPatchRingsize() +
        patchTables->GetFullGregoryPatches().GetSize()/patchTables->GetGregoryPatchRingsize() +
        patchTables->GetFullBoundaryGregoryPatches().GetSize()/patchTables->GetGregoryPatchRingsize();

    for (int p=0; p<5; ++p) {
        totalPatchIndices +=
            patchTables->GetTransitionRegularPatches(p).GetSize();

        totalPatchLevels +=
            patchTables->GetTransitionRegularPatches(p).GetSize()/patchTables->GetRegularPatchRingsize();

        for (int r=0; r<4; ++r) {
            totalPatchIndices +=
                patchTables->GetTransitionBoundaryPatches(p, r).GetSize() +
                patchTables->GetTransitionCornerPatches(p, r).GetSize();

            totalPatchLevels +=
                patchTables->GetTransitionBoundaryPatches(p, r).GetSize()/patchTables->GetBoundaryPatchRingsize() +
                patchTables->GetTransitionCornerPatches(p, r).GetSize()/patchTables->GetCornerPatchRingsize();
        }
    }

    // Allocate and fill index buffer.
    glGenBuffers(1, &patchIndexBuffer);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, patchIndexBuffer);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER,
        totalPatchIndices * sizeof(unsigned int), NULL, GL_STATIC_DRAW);

#if defined(GL_ARB_texture_buffer_object) || defined(GL_VERSION_3_1)
    GLuint patchLevelBuffer = 0;
    glGenBuffers(1, &patchLevelBuffer);
    glBindBuffer(GL_TEXTURE_BUFFER, patchLevelBuffer);
    glBufferData(GL_TEXTURE_BUFFER,
        totalPatchLevels * sizeof(unsigned char), NULL, GL_STATIC_DRAW);
#endif

    // Allocate ptex coordinate buffer if requested
    GLuint ptexCoordinateBuffer = 0;
    if (requirePtexCoordinates) {
#if defined(GL_ARB_texture_buffer_object) || defined(GL_VERSION_3_1)
        glGenTextures(1, &ptexCoordinateTextureBuffer);
        glGenBuffers(1, &ptexCoordinateBuffer);
        glBindBuffer(GL_ARRAY_BUFFER, ptexCoordinateBuffer);
        glBufferData(GL_ARRAY_BUFFER,
            totalPatchLevels * sizeof(int) * 2, NULL, GL_STATIC_DRAW);
#endif
    }

    // Allocate fvar data buffer if requested
    GLuint fvarDataBuffer = 0;
    if (requireFVarData) {
#if defined(GL_ARB_texture_buffer_object) || defined(GL_VERSION_3_1)
        glGenTextures(1, &fvarDataTextureBuffer);
        glGenBuffers(1, &fvarDataBuffer);
        glBindBuffer(GL_UNIFORM_BUFFER, fvarDataBuffer);
        glBufferData(GL_UNIFORM_BUFFER,
            totalPatchLevels * sizeof(float) * farMesh->GetTotalFVarWidth()*4, NULL, GL_STATIC_DRAW);
#endif
    }

    int indexBase = 0;
    int levelBase = 0;
    int maxValence = patchTables->GetMaxValence();

    _AppendPatchArray(&indexBase, &levelBase,
                        patchTables->GetFullRegularPatches(),
                        patchTables->GetRegularPatchRingsize(),
                        patchTables->GetFullRegularPtexCoordinates(),
                        patchTables->GetFullRegularFVarData(),
                        farMesh->GetTotalFVarWidth(),
                        OsdPatchDescriptor(kRegular, 0, 0, 0, 0), 0);
    _AppendPatchArray(&indexBase, &levelBase,
                        patchTables->GetFullBoundaryPatches(),
                        patchTables->GetBoundaryPatchRingsize(),
                        patchTables->GetFullBoundaryPtexCoordinates(),
                        patchTables->GetFullBoundaryFVarData(),
                        farMesh->GetTotalFVarWidth(),
                        OsdPatchDescriptor(kBoundary, 0, 0, 0, 0), 0);
    _AppendPatchArray(&indexBase, &levelBase,
                        patchTables->GetFullCornerPatches(),
                        patchTables->GetCornerPatchRingsize(),
                        patchTables->GetFullCornerPtexCoordinates(),
                        patchTables->GetFullCornerFVarData(),
                        farMesh->GetTotalFVarWidth(),
                        OsdPatchDescriptor(kCorner, 0, 0, 0, 0), 0);
    _AppendPatchArray(&indexBase, &levelBase,
                        patchTables->GetFullGregoryPatches(),
                        patchTables->GetGregoryPatchRingsize(),
                        patchTables->GetFullGregoryPtexCoordinates(),
                        patchTables->GetFullGregoryFVarData(),
                        farMesh->GetTotalFVarWidth(),
                        OsdPatchDescriptor(kGregory, 0, 0,
                                           maxValence, numElements), 0);
    _AppendPatchArray(&indexBase, &levelBase,
                        patchTables->GetFullBoundaryGregoryPatches(),
                        patchTables->GetGregoryPatchRingsize(),
                        patchTables->GetFullBoundaryGregoryPtexCoordinates(),
                        patchTables->GetFullBoundaryGregoryFVarData(),
                        farMesh->GetTotalFVarWidth(),
                        OsdPatchDescriptor(kBoundaryGregory, 0, 0,
                                           maxValence, numElements),
                        (int)patchTables->GetFullGregoryPatches().GetSize());

    for (int p=0; p<5; ++p) {
        _AppendPatchArray(&indexBase, &levelBase,
                        patchTables->GetTransitionRegularPatches(p),
                        patchTables->GetRegularPatchRingsize(),
                        patchTables->GetTransitionRegularPtexCoordinates(p),
                        patchTables->GetTransitionRegularFVarData(p),
                        farMesh->GetTotalFVarWidth(),
                        OsdPatchDescriptor(kTransitionRegular, p, 0, 0, 0), 0);
        for (int r=0; r<4; ++r) {
            _AppendPatchArray(&indexBase, &levelBase,
                        patchTables->GetTransitionBoundaryPatches(p, r),
                        patchTables->GetBoundaryPatchRingsize(),
                        patchTables->GetTransitionBoundaryPtexCoordinates(p, r),
                        patchTables->GetTransitionBoundaryFVarData(p, r),
                        farMesh->GetTotalFVarWidth(),
                        OsdPatchDescriptor(kTransitionBoundary, p, r, 0, 0), 0);
            _AppendPatchArray(&indexBase, &levelBase,
                        patchTables->GetTransitionCornerPatches(p, r),
                        patchTables->GetCornerPatchRingsize(),
                        patchTables->GetTransitionCornerPtexCoordinates(p, r),
                        patchTables->GetTransitionCornerFVarData(p, r),
                        farMesh->GetTotalFVarWidth(),
                        OsdPatchDescriptor(kTransitionCorner, p, r, 0, 0), 0);
        }
    }

#if defined(GL_ARB_texture_buffer_object) || defined(GL_VERSION_3_1)
    // finalize level texture buffer
    glGenTextures(1, &patchLevelTextureBuffer);
    glBindTexture(GL_TEXTURE_BUFFER, patchLevelTextureBuffer);
    glTexBuffer(GL_TEXTURE_BUFFER, GL_R8I, patchLevelBuffer);
    glDeleteBuffers(1, &patchLevelBuffer);

    // finalize ptex coordinate texture buffer
    glBindBuffer(GL_ARRAY_BUFFER, 0);
    if (requirePtexCoordinates) {
        glBindTexture(GL_TEXTURE_BUFFER, ptexCoordinateTextureBuffer);
        glTexBuffer(GL_TEXTURE_BUFFER, GL_RG32I, ptexCoordinateBuffer);
        glDeleteBuffers(1, &ptexCoordinateBuffer);
    }
    // finalize fvar data texture buffer
    glBindBuffer(GL_UNIFORM_BUFFER, 0);
    if (requireFVarData) {
        glBindTexture(GL_TEXTURE_BUFFER, fvarDataTextureBuffer);
        glTexBuffer(GL_TEXTURE_BUFFER, GL_R32F, fvarDataBuffer);
        glDeleteBuffers(1, &fvarDataBuffer);
    }
#endif

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
#if defined(GL_ARB_texture_buffer_object) || defined(GL_VERSION_3_1)
    glBindBuffer(GL_TEXTURE_BUFFER, 0);
#endif

    // allocate and initialize additional buffer data
    FarPatchTables::VertexValenceTable const &
        valenceTable = patchTables->GetVertexValenceTable();

    if (not valenceTable.empty()) {
#if defined(GL_ARB_texture_buffer_object) || defined(GL_VERSION_3_1)
        GLuint buffer = 0;
        glGenBuffers(1, &buffer);
        glBindBuffer(GL_TEXTURE_BUFFER, buffer);
        glBufferData(GL_TEXTURE_BUFFER,
                valenceTable.size() * sizeof(unsigned int),
                &valenceTable[0], GL_STATIC_DRAW);

        glGenTextures(1, &vertexValenceTextureBuffer);
        glBindTexture(GL_TEXTURE_BUFFER, vertexValenceTextureBuffer);
        glTexBuffer(GL_TEXTURE_BUFFER, GL_R32I, buffer);
        glDeleteBuffers(1, &buffer);

        glGenTextures(1, &vertexTextureBuffer);
        glBindTexture(GL_TEXTURE_BUFFER, vertexTextureBuffer);
        glTexBuffer(GL_TEXTURE_BUFFER, GL_R32F, vbo);

        glBindBuffer(GL_TEXTURE_BUFFER, 0);
#endif
    }

    FarPatchTables::QuadOffsetTable const &
        quadOffsetTable = patchTables->GetQuadOffsetTable();

    if (not quadOffsetTable.empty()) {
#if defined(GL_ARB_texture_buffer_object) || defined(GL_VERSION_3_1)
        GLuint buffer = 0;
        glGenBuffers(1, &buffer);
        glBindBuffer(GL_TEXTURE_BUFFER, buffer);
        glBufferData(GL_TEXTURE_BUFFER,
                quadOffsetTable.size() * sizeof(unsigned int),
                &quadOffsetTable[0], GL_STATIC_DRAW);

        glGenTextures(1, &quadOffsetTextureBuffer);
        glBindTexture(GL_TEXTURE_BUFFER, quadOffsetTextureBuffer);
        glTexBuffer(GL_TEXTURE_BUFFER, GL_R32I, buffer);
        glDeleteBuffers(1, &buffer);

        glBindBuffer(GL_TEXTURE_BUFFER, 0);
#endif
    }

    return true;
}
void MyGLWidget::createBuffers ()
{
  // Carreguem el model de l'OBJ - Atenció! Abans de crear els buffers!
  patr.load("./models/Patricio.obj");

  // Calculem la capsa contenidora del model
  calculaCapsaModel ();
  
  // Creació del Vertex Array Object del Patricio
  glGenVertexArrays(1, &VAO_Patr);
  glBindVertexArray(VAO_Patr);

  // Creació dels buffers del model patr
  // Buffer de posicions
  glGenBuffers(1, &VBO_PatrPos);
  glBindBuffer(GL_ARRAY_BUFFER, VBO_PatrPos);
  glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*patr.faces().size()*3*3, patr.VBO_vertices(), GL_STATIC_DRAW);

  // Activem l'atribut vertexLoc
  glVertexAttribPointer(vertexLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
  glEnableVertexAttribArray(vertexLoc);

  // Buffer de normals
  glGenBuffers(1, &VBO_PatrNorm);
  glBindBuffer(GL_ARRAY_BUFFER, VBO_PatrNorm);
  glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*patr.faces().size()*3*3, patr.VBO_normals(), GL_STATIC_DRAW);

  glVertexAttribPointer(normalLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
  glEnableVertexAttribArray(normalLoc);

  // En lloc del color, ara passem tots els paràmetres dels materials
  // Buffer de component ambient
  glGenBuffers(1, &VBO_PatrMatamb);
  glBindBuffer(GL_ARRAY_BUFFER, VBO_PatrMatamb);
  glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*patr.faces().size()*3*3, patr.VBO_matamb(), GL_STATIC_DRAW);

  glVertexAttribPointer(matambLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
  glEnableVertexAttribArray(matambLoc);

  // Buffer de component difusa
  glGenBuffers(1, &VBO_PatrMatdiff);
  glBindBuffer(GL_ARRAY_BUFFER, VBO_PatrMatdiff);
  glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*patr.faces().size()*3*3, patr.VBO_matdiff(), GL_STATIC_DRAW);

  glVertexAttribPointer(matdiffLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
  glEnableVertexAttribArray(matdiffLoc);

  // Buffer de component especular
  glGenBuffers(1, &VBO_PatrMatspec);
  glBindBuffer(GL_ARRAY_BUFFER, VBO_PatrMatspec);
  glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*patr.faces().size()*3*3, patr.VBO_matspec(), GL_STATIC_DRAW);

  glVertexAttribPointer(matspecLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
  glEnableVertexAttribArray(matspecLoc);

  // Buffer de component shininness
  glGenBuffers(1, &VBO_PatrMatshin);
  glBindBuffer(GL_ARRAY_BUFFER, VBO_PatrMatshin);
  glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*patr.faces().size()*3, patr.VBO_matshin(), GL_STATIC_DRAW);

  glVertexAttribPointer(matshinLoc, 1, GL_FLOAT, GL_FALSE, 0, 0);
  glEnableVertexAttribArray(matshinLoc);


  //LEGOMAN

  // Carreguem el model de l'OBJ - Atenció! Abans de crear els buffers!
  lego.load("./models/legoman.obj");

    // Calculem la capsa contenidora del model
    calculaCapsaCirc ();

    // Creació del Vertex Array Object del Legoman
    glGenVertexArrays(1, &VAO_lego);
    glBindVertexArray(VAO_lego);

    // Creació dels buffers del model lego
    // Buffer de posicions
    glGenBuffers(1, &VBO_legoPos);
    glBindBuffer(GL_ARRAY_BUFFER, VBO_legoPos);
    glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*lego.faces().size()*3*3, lego.VBO_vertices(), GL_STATIC_DRAW);

    // Activem l'atribut vertexLoc
    glVertexAttribPointer(vertexLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
    glEnableVertexAttribArray(vertexLoc);

    // Buffer de normals
    glGenBuffers(1, &VBO_legoNorm);
    glBindBuffer(GL_ARRAY_BUFFER, VBO_legoNorm);
    glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*lego.faces().size()*3*3, lego.VBO_normals(), GL_STATIC_DRAW);

    glVertexAttribPointer(normalLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
    glEnableVertexAttribArray(normalLoc);

    // En lloc del color, ara passem tots els paràmetres dels materials
    // Buffer de component ambient
    glGenBuffers(1, &VBO_legoMatamb);
    glBindBuffer(GL_ARRAY_BUFFER, VBO_legoMatamb);
    glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*lego.faces().size()*3*3, lego.VBO_matamb(), GL_STATIC_DRAW);

    glVertexAttribPointer(matambLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
    glEnableVertexAttribArray(matambLoc);

    // Buffer de component difusa
    glGenBuffers(1, &VBO_legoMatdiff);
    glBindBuffer(GL_ARRAY_BUFFER, VBO_legoMatdiff);
    glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*lego.faces().size()*3*3, lego.VBO_matdiff(), GL_STATIC_DRAW);

    glVertexAttribPointer(matdiffLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
    glEnableVertexAttribArray(matdiffLoc);

    // Buffer de component especular
    glGenBuffers(1, &VBO_legoMatspec);
    glBindBuffer(GL_ARRAY_BUFFER, VBO_legoMatspec);
    glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*lego.faces().size()*3*3, lego.VBO_matspec(), GL_STATIC_DRAW);

    glVertexAttribPointer(matspecLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
    glEnableVertexAttribArray(matspecLoc);

    // Buffer de component shininness
    glGenBuffers(1, &VBO_legoMatshin);
    glBindBuffer(GL_ARRAY_BUFFER, VBO_legoMatshin);
    glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*lego.faces().size()*3, lego.VBO_matshin(), GL_STATIC_DRAW);

    glVertexAttribPointer(matshinLoc, 1, GL_FLOAT, GL_FALSE, 0, 0);
    glEnableVertexAttribArray(matshinLoc);


  // Dades del terra

  // VBO amb la posició dels vèrtexs
  glm::vec3 posterra[4] = {
	glm::vec3( 10.0, 0.0, -10.0),
	glm::vec3( 10.0, 0.0,  10.0),
	glm::vec3(-10.0, 0.0, -10.0),
	glm::vec3(-10.0, 0.0,  10.0)
  }; 

  // VBO amb la normal de cada vèrtex
  glm::vec3 norm (0,1,0);
  glm::vec3 normterra[4] = {
	norm, norm, norm, norm
  };

  // Definim el material del terra
  glm::vec3 amb(0.1,0.09,0.);
  glm::vec3 diff(0.,0.8,0.);
  glm::vec3 spec(1.,1.,1.);
  float shin = 100;

  // Fem que aquest material afecti a tots els vèrtexs per igual
  glm::vec3 matambterra[4] = {
	amb, amb, amb, amb
  };
  glm::vec3 matdiffterra[4] = {
	diff, diff, diff, diff
  };
  glm::vec3 matspecterra[4] = {
	spec, spec, spec, spec
  };
  float matshinterra[4] = {
	shin, shin, shin, shin
  };

// Creació del Vertex Array Object del terra
  glGenVertexArrays(1, &VAO_Terra);
  glBindVertexArray(VAO_Terra);

  glGenBuffers(1, &VBO_TerraPos);
  glBindBuffer(GL_ARRAY_BUFFER, VBO_TerraPos);
  glBufferData(GL_ARRAY_BUFFER, sizeof(posterra), posterra, GL_STATIC_DRAW);

  // Activem l'atribut vertexLoc
  glVertexAttribPointer(vertexLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
  glEnableVertexAttribArray(vertexLoc);

  glGenBuffers(1, &VBO_TerraNorm);
  glBindBuffer(GL_ARRAY_BUFFER, VBO_TerraNorm);
  glBufferData(GL_ARRAY_BUFFER, sizeof(normterra), normterra, GL_STATIC_DRAW);

  // Activem l'atribut normalLoc
  glVertexAttribPointer(normalLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
  glEnableVertexAttribArray(normalLoc);

  // En lloc del color, ara passem tots els paràmetres dels materials
  // Buffer de component ambient
  glGenBuffers(1, &VBO_TerraMatamb);
  glBindBuffer(GL_ARRAY_BUFFER, VBO_TerraMatamb);
  glBufferData(GL_ARRAY_BUFFER, sizeof(matambterra), matambterra, GL_STATIC_DRAW);

  glVertexAttribPointer(matambLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
  glEnableVertexAttribArray(matambLoc);

  // Buffer de component difusa
  glGenBuffers(1, &VBO_TerraMatdiff);
  glBindBuffer(GL_ARRAY_BUFFER, VBO_TerraMatdiff);
  glBufferData(GL_ARRAY_BUFFER, sizeof(matdiffterra), matdiffterra, GL_STATIC_DRAW);

  glVertexAttribPointer(matdiffLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
  glEnableVertexAttribArray(matdiffLoc);

  // Buffer de component especular
  glGenBuffers(1, &VBO_TerraMatspec);
  glBindBuffer(GL_ARRAY_BUFFER, VBO_TerraMatspec);
  glBufferData(GL_ARRAY_BUFFER, sizeof(matspecterra), matspecterra, GL_STATIC_DRAW);

  glVertexAttribPointer(matspecLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
  glEnableVertexAttribArray(matspecLoc);

  // Buffer de component shininness
  glGenBuffers(1, &VBO_TerraMatshin);
  glBindBuffer(GL_ARRAY_BUFFER, VBO_TerraMatshin);
  glBufferData(GL_ARRAY_BUFFER, sizeof(matshinterra), matshinterra, GL_STATIC_DRAW);

  glVertexAttribPointer(matshinLoc, 1, GL_FLOAT, GL_FALSE, 0, 0);
  glEnableVertexAttribArray(matshinLoc);

  glBindVertexArray(0);
}
Beispiel #25
0
int OpenGl::SetUpOpenGl()
{
	const char* vertex_shader =
	"#version 330\n"
	"attribute vec3 vp;"
	"void main () {"
	"	gl_Position = vec4 (vp, 1.0);"
	"}";
	
	const char* fragment_shader =
	"#version 330\n"
	"void main () {"
	"	gl_FragColor = vec4 (0.5, 0.0, 0.5, 1.0);"
	"}";
	
	if(!glfwInit())
	{
		fprintf(stderr, "Error: could not start GLFW3\n");
		return 1;
	}
	
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
	
	window = glfwCreateWindow(640, 480, "Engine", NULL, NULL);
	if(!window)
	{
		fprintf(stderr, "ErrorL Could Not open Window\n");
		glfwTerminate();
		return 1;
	}
	
	glfwMakeContextCurrent(window);
	glewExperimental = GL_TRUE;
	glewInit();
	
	renderer = glGetString(GL_RENDERER);
	version = glGetString(GL_VERSION);
	printf("Renderer: %s\n", renderer);
	printf("OpenGL version supported %s\n", version);
	
	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LESS);
	
	glGenBuffers(1, &vbo);
	glBindBuffer(GL_ARRAY_BUFFER, vbo);
	glBufferData(GL_ARRAY_BUFFER, 9 * sizeof(GLfloat), points, GL_STATIC_DRAW);
	
	glGenVertexArrays(1, &vao);
	glBindVertexArray(vao);
	glEnableVertexAttribArray(0);
	glBindBuffer(GL_ARRAY_BUFFER, vbo);
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, NULL);
	
	useShader = Shaders::Instance()->getShader("text");
	if(useShader->shader_program == 0)
	{
		printf("f**k OFF MATE");
	}	
	return 0;
	
}
void RenderCube()
{
    // Initialize (if necessary)
    if (cubeVAO == 0)
    {
        GLfloat vertices[] = {
            // Back face
            -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, // Bottom-left
            0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, // top-right
            0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, // bottom-right
            0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f,  // top-right
            -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f,  // bottom-left
            -0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f,// top-left
            // Front face
            -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, // bottom-left
            0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f,  // bottom-right
            0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f,  // top-right
            0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, // top-right
            -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f,  // top-left
            -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,  // bottom-left
            // Left face
            -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, // top-right
            -0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f, // top-left
            -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f,  // bottom-left
            -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, // bottom-left
            -0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f,  // bottom-right
            -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, // top-right
            // Right face
            0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, // top-left
            0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, // bottom-right
            0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, // top-right
            0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f,  // bottom-right
            0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f,  // top-left
            0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, // bottom-left
            // Bottom face
            -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, // top-right
            0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 1.0f, // top-left
            0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f,// bottom-left
            0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, // bottom-left
            -0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, // bottom-right
            -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, // top-right
            // Top face
            -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f,// top-left
            0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, // bottom-right
            0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, // top-right
            0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, // bottom-right
            -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f,// top-left
            -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f // bottom-left
        };
        glGenVertexArrays(1, &cubeVAO);
        glGenBuffers(1, &cubeVBO);
        // Fill buffer
        glBindBuffer(GL_ARRAY_BUFFER, cubeVBO);
        glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
        // Link vertex attributes
        glBindVertexArray(cubeVAO);
        glEnableVertexAttribArray(0);
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)0);
        glEnableVertexAttribArray(1);
        glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
        glEnableVertexAttribArray(2);
        glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(6 * sizeof(GLfloat)));
        glBindBuffer(GL_ARRAY_BUFFER, 0);
        glBindVertexArray(0);
    }
    // Render Cube
    glBindVertexArray(cubeVAO);
    glDrawArrays(GL_TRIANGLES, 0, 36);
    glBindVertexArray(0);
}
Beispiel #27
0
	MapAndSync(u32 type, u32 size) : StreamBuffer(type, size) {
		CreateFences();
		glBindBuffer(m_buffertype, m_buffer);
		glBufferData(m_buffertype, m_size, nullptr, GL_STREAM_DRAW);
	}
Beispiel #28
0
void FiberRenderer::initGeometry()
{
    if ( m_isInitialized )
    {
        return;
    }
    qDebug() << "create fiber vbo's...";

    std::vector<float>verts;

    try
    {
        verts.reserve( m_numPoints * 6 );
    }
    catch ( std::bad_alloc& )
    {
        qCritical() << "***error*** failed to allocate enough memory for vbo";
        exit ( 0 );
    }


    for ( unsigned int i = 0; i < m_fibs->size(); ++i )
    {
        Fib fib = m_fibs->at(i);

        if ( fib.length() < 2 )
        {
            printf( "fib with size < 2 detected" );
            continue;
        }

        QVector3D lineStart = fib.firstVert();
        QVector3D lineEnd = fib.lastVert();

        // push back the first vertex, done seperately because of nomal calculation
        verts.push_back( lineStart.x() );
        verts.push_back( lineStart.y() );
        verts.push_back( lineStart.z() );

        QVector3D secondVert = fib.getVert( 1 );

        QVector3D localColor( lineStart.x() - secondVert.x(), lineStart.y() - secondVert.y(), lineStart.z() - secondVert.z() );
        localColor.normalize();

        verts.push_back( localColor.x() );
        verts.push_back( localColor.y() );
        verts.push_back( localColor.z() );

        for ( unsigned int k = 1; k < fib.length() - 1; ++k )
        {
            verts.push_back( fib[k].x() );
            verts.push_back( fib[k].y() );
            verts.push_back( fib[k].z() );

            QVector3D localColor( fib[k-1].x() - fib[k+1].x(), fib[k-1].y() - fib[k+1].y(), fib[k-1].z() - fib[k+1].z() );
            localColor.normalize();

            verts.push_back( localColor.x() );
            verts.push_back( localColor.y() );
            verts.push_back( localColor.z() );

        }

        // push back the last vertex, done seperately because of nomal calculation
        verts.push_back( lineEnd.x() );
        verts.push_back( lineEnd.y() );
        verts.push_back( lineEnd.z() );

        QVector3D sec2last = fib[ fib.length() - 2 ];
        QVector3D localColor2( sec2last.x() - lineEnd.x(), sec2last.y() - lineEnd.y(), sec2last.z() - lineEnd.z() );
        localColor.normalize();

        verts.push_back( localColor2.x() );
        verts.push_back( localColor2.y() );
        verts.push_back( localColor2.z() );
    }

    glBindBuffer( GL_ARRAY_BUFFER, vbo );
    glBufferData( GL_ARRAY_BUFFER, verts.size() * sizeof(GLfloat), verts.data(), GL_STATIC_DRAW );
    glBindBuffer( GL_ARRAY_BUFFER, 0 );
    verts.clear();

    m_pointsPerLine.resize( m_fibs->size() );
    m_startIndexes.resize( m_fibs->size() );

    int currentStart = 0;
    for ( unsigned int i = 0; i < m_fibs->size(); ++i )
    {
        m_pointsPerLine[i] = m_fibs->at( i ).length();
        m_startIndexes[i] = currentStart;
        currentStart += m_pointsPerLine[i];
    }

    updateExtraData( 0 );

    qDebug() << "create fiber vbo's done";

    m_numPoints = verts.size() / 6;

    m_isInitialized = true;
}
Beispiel #29
0
	void Unmap(u32 used_size) override {
		glBufferData(m_buffertype, used_size, m_pointer, GL_STREAM_DRAW);
	}
Beispiel #30
0
void Graphic::Initialize()
{
	GLuint Vao;

	glfwInit();

	glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3);
	glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 3);
	glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

	glfwOpenWindow( 800, 600, 0, 0, 0, 0, 0, 0, GLFW_WINDOW );

	glewExperimental = GL_TRUE;
	glewInit();

	glfwSetWindowTitle( "Hej!" );

	glEnable( GL_DEPTH_TEST );
	glEnable( GL_CULL_FACE );
	glEnable( GL_BLEND );

	glCullFace( GL_BACK );
	glFrontFace( GL_CCW );
	glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );

	glClearColor( 0.5f, 0.5f, 0.5f, 0.5f );
	glDepthFunc( GL_LESS );

	glm::vec3 eye( 0.f, 0.f, 5.f ), centre( 0.f, 0.f, 0.f ), up( 0.f, 1.f, 0.f );
	viewMatrix = glm::lookAt(eye, centre, up);


	shaderProgram = CreateShader( "Source/shader.vertex", "Source/shader.fragment" );
	shaderLine = CreateShader( "Source/line.vertex", "Source/line.fragment" );
	shaderText = CreateShader( "Source/text.vertex", "Source/text.fragment" );

	Texture t;
	glGenTextures( (int)Type::Size + 43, glTexture );

	int i = 0;

	#define DEFAULT_TEXTURE_OPTIONS \
		glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); \
		glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST ); \
		glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB8, t.width, t.height, 0, GL_BGR, GL_UNSIGNED_BYTE, &t[0] );

#define FOO( CLASS, ARRAY, NUMBER ) \
	t.LoadBmp( #CLASS ".bmp" ); \
	assert( i == NUMBER ); \
	glBindTexture( GL_TEXTURE_2D, glTexture[i++] ); \
	DEFAULT_TEXTURE_OPTIONS
	TYPE_TABLE
#undef FOO


	t.LoadBmp( "Mountain.bmp" );
	mountain = i;
	glBindTexture( GL_TEXTURE_2D, glTexture[i++] );
	DEFAULT_TEXTURE_OPTIONS

	t.LoadBmp( "Forest.bmp" );
	forest = i;
	glBindTexture( GL_TEXTURE_2D, glTexture[i++] );
	DEFAULT_TEXTURE_OPTIONS


	// Load char numbers
	for( char j(0); j < 10; j++ )
	{
		char_textures[ std::to_string(j)[0] ] = i;
		t.LoadBmp( "Font/" + std::to_string(j) + ".bmp" );
		glBindTexture( GL_TEXTURE_2D, glTexture[i++] );
		DEFAULT_TEXTURE_OPTIONS
	}
	// Load char letters
	for( char j(0); j < 26; j++ )
	{
		char_textures[ 'A'+j ] = i;
		std::stringstream s;
		s << "Font/" << (char)('A'+j) << ".bmp";
		t.LoadBmp( s.str() );
		glBindTexture( GL_TEXTURE_2D, glTexture[i++] );
		DEFAULT_TEXTURE_OPTIONS
	}
	char_textures[ '/' ] = i;
	t.LoadBmp( "Font/forward_slash.bmp" );
	glBindTexture( GL_TEXTURE_2D, glTexture[i++] );
	DEFAULT_TEXTURE_OPTIONS

	char_textures[ '+' ] = i;
	t.LoadBmp( "Font/plus.bmp" );
	glBindTexture( GL_TEXTURE_2D, glTexture[i++] );
	DEFAULT_TEXTURE_OPTIONS

	char_textures[ '-' ] = i;
	t.LoadBmp( "Font/minus.bmp" );
	glBindTexture( GL_TEXTURE_2D, glTexture[i++] );
	DEFAULT_TEXTURE_OPTIONS

	char_textures[ '#' ] = i;
	t.LoadBmp( "food.bmp" );
	glBindTexture( GL_TEXTURE_2D, glTexture[i++] );
	DEFAULT_TEXTURE_OPTIONS

	char_textures[ '$' ] = i;
	t.LoadBmp( "money.bmp" );
	glBindTexture( GL_TEXTURE_2D, glTexture[i++] );
	DEFAULT_TEXTURE_OPTIONS

	#undef DEFAULT_TEXTURE_OPTIONS


	lines.push_back( Line( vertexs[0], vertexs[1], vertexs[3], vertexs[4] ) );
	lines.push_back( Line( vertexs[6], vertexs[7], vertexs[9], vertexs[10] ) );



	// Vertex, normal, texture, text
	glGenBuffers( 3, Vbo );
	int size = 4 * sizeof(float);

	glBindBuffer(GL_ARRAY_BUFFER, Vbo[0]);
	glBufferData(GL_ARRAY_BUFFER, lines.size() * 2 * 3 * sizeof(float), &lines[0], GL_DYNAMIC_DRAW);

	glBindBuffer(GL_ARRAY_BUFFER, Vbo[1]);
	glBufferData(GL_ARRAY_BUFFER, size * 3, &normals[0], GL_STATIC_DRAW);

	glBindBuffer(GL_ARRAY_BUFFER, Vbo[2]);
	glBufferData(GL_ARRAY_BUFFER, size * 2, &textureCoordinates[0], GL_STATIC_DRAW);


	glGenVertexArrays(1, &Vao);
	glBindVertexArray(Vao);

	glEnableVertexAttribArray(0);
	glEnableVertexAttribArray(1);
	glEnableVertexAttribArray(2);

	GLubyte* null = 0;

	glBindBuffer(GL_ARRAY_BUFFER, Vbo[0]);
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, null);

	glBindBuffer(GL_ARRAY_BUFFER, Vbo[1]);
	glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, null);

	glBindBuffer(GL_ARRAY_BUFFER, Vbo[2]);
	glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, null);


	glBindVertexArray(Vao);
}