Draw triangle with glDrawArray function

352 views Asked by At

I want to draw an triangle in opengl with glDrawArrays() function. Following is my code: .cpp file:

        void linedr2::initializeGL()
   {
            glClearColor(0, 0, 0, 1.0);
            glMatrixMode(GL_PROJECTION);
            glLoadIdentity();
            glOrtho(-10,10,-10,10,1,10);

             vertices[0].x = 10;
            vertices[0].y = 5;

            // Vertex 2
           vertices[1].x = -10;
           vertices[1].y = 3;

                // Vertex 3
          vertices[2].x = 5;
         vertices[2].y = -5;

       }

    void linedr2::paintGL()
     {
              int num_indices = 2;
             glEnableClientState( GL_VERTEX_ARRAY );

               glVertexPointer( 2, GL_FLOAT, 0, vertices);
              glDrawArrays(GL_TRIANGLES, 0, num_indices);
               glDisableClientState( GL_VERTEX_ARRAY );


         }

.header file:

         #include <QWidget>
         #include <QOpenGLWidget>
         #include <gl/GLU.h>
         #include <gl/GL.h>

         class linedr2: public QOpenGLWidget
       {
        public:
         linedr2(QWidget *parent = 0);
         ~linedr2();

       struct vertex
    {
       GLfloat x, y; //z;
    };
         vertex *vertices = new vertex[2];

         protected:
           void initializeGL();
         void paintGL();
         void resizeGL(int w, int h);


       };

With this code, I am just getting an blank window. No points are getting plotted. What I am doing wrong? Is there anything wrong in my glDrawArray function?

1

There are 1 answers

0
Paltoquet On BEST ANSWER

I don't know what is happening when you don't specify the z component of your vertices.

But one thing is sure

glOrtho(-10,10,-10,10,1,10);

will display everything belonging inside the box. If your z component is 0 it won't appear.

try replace it by something like:

glOrtho(-10,10,-10,10,-1,10);