OpenGL learning road 3----Draw a triangle

According to the tutorial: ogldev starts from scratch step by step and records the learning process

normalized coordinates

When we draw graphics on the screen, it is in a normalized space, which is the following figure

write picture description here

You can see that the coordinates of the lower left corner of the drawing window are (-1.0,-1.0) to the upper right corner coordinates are (1.0,1.0)

code explanation

opengl_math.h:

#ifndef __OPENGL_MATH_H
#define __OPENGL_MATH_H

//向量        
typedef float   Vector3f[3];                

//向量赋值
inline void LoadVector3(Vector3f v, const float x, const float y, const float z)
{
    v[0] = x; v[1] = y; v[2] = z;
}

#endif
#include <stdio.h>
#include <gl/glew.h>
#include <gl/freeglut.h>
#include "opengl_math.h"

GLuint VBO;

static void Render()
{
    glClear(GL_COLOR_BUFFER_BIT);

    glEnableVertexAttribArray(0);

    glBindBuffer(GL_ARRAY_BUFFER, VBO);

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

    glDrawArrays(GL_TRIANGLES, 0, 3);

    glDisableVertexAttribArray(0);

    glutSwapBuffers();
}

static void CreateVertexBuffer()
{
    Vector3f Vertices[3];

    LoadVector3(Vertices[0], -0.5f, -0.5f, 0.0f);
    LoadVector3(Vertices[1], 0.5f, -0.5f, 0.0f);
    LoadVector3(Vertices[2], 0.0f, 0.5f, 0.0f);

    glGenBuffers(1, &VBO);

    glBindBuffer(GL_ARRAY_BUFFER, VBO);

    glBufferData(GL_ARRAY_BUFFER, sizeof(Vertices), Vertices, GL_STATIC_DRAW);
}
int main(int argc, char ** argv) {

    glutInit(&argc, argv);

    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA);

    glutInitWindowSize(480, 320);
    glutInitWindowPosition(100, 100);
    glutCreateWindow("First Triangle");

    glutDisplayFunc(Render);

    GLenum res = glewInit();
    if (res != GLEW_OK) {
        fprintf(stderr, "Error: '%s'\n", glewGetErrorString(res));
        return 1;
    }

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

    CreateVertexBuffer();

    glutMainLoop();

    return 0;
}

The code in this section is only slightly different from the previous section, and only the difference is mentioned here.

Vector3f Vertices[3];

    LoadVector3(Vertices[0], -0.5f, -0.5f, 0.0f);
    LoadVector3(Vertices[1], 0.5f, -0.5f, 0.0f);
    LoadVector3(Vertices[2], 0.0f, 0.5f, 0.0f);

Here an array containing three vertices is defined, and values ​​are assigned to them

glDrawArrays(GL_TRIANGLES, 0, 3); 

The first parameter of drawing geometry becomes the drawing triangle, and the number of fixed points becomes 3

operation result:

write picture description here

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324892178&siteId=291194637