OpenGL array of points

12,039

Solution 1

Where are you setting the values for x[0], x[1], y[0], and y[1]?

If it's only drawing one point in the center, it sounds like the values are set to 0 for all four of those variables. Be sure to initialize their values before you reference them in your call to gVertex2f().

Solution 2

Requires GLUT for window and context management:

#include <GL/glut.h>
#include <vector>
#include <cstdlib>

struct Point
{
    float x, y;
    unsigned char r, g, b, a;
};
std::vector< Point > points;

void display(void)
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(-50, 50, -50, 50, -1, 1);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    // draw
    glColor3ub( 255, 255, 255 );
    glEnableClientState( GL_VERTEX_ARRAY );
    glEnableClientState( GL_COLOR_ARRAY );
    glVertexPointer( 2, GL_FLOAT, sizeof(Point), &points[0].x );
    glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof(Point), &points[0].r );
    glPointSize( 3.0 );
    glDrawArrays( GL_POINTS, 0, points.size() );
    glDisableClientState( GL_VERTEX_ARRAY );
    glDisableClientState( GL_COLOR_ARRAY );

    glFlush();
    glutSwapBuffers();
}

void reshape(int w, int h)
{
    glViewport(0, 0, w, h);
}

int main(int argc, char **argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE);

    glutInitWindowSize(640,480);
    glutCreateWindow("Random Points");

    glutDisplayFunc(display);
    glutReshapeFunc(reshape);

     // populate points
    for( size_t i = 0; i < 1000; ++i )
    {
        Point pt;
        pt.x = -50 + (rand() % 100);
        pt.y = -50 + (rand() % 100);
        pt.r = rand() % 255;
        pt.g = rand() % 255;
        pt.b = rand() % 255;
        pt.a = 255;
        points.push_back(pt);
    }    

    glutMainLoop();
    return 0;
}

Screenshot

Solution 3

Do you define what x[i] and y[i] are? Otherwise they will be set to 0 automatically (hence the centering). Also, creating the arrays with two elements but accessing 10 elements is very bad since you are accessing memory locations that you do not have control over.

You should do something like :

GLint NumberOfPoints = 10;
GLfloat x[10],y[10];

for(int i = 0; i < NumberOfPoints; i++){
    x[i] = y[i] = (GLfloat) i;
}

glBegin( GL_POINTS );

for ( int i = 0; i < NumberOfPoints; ++i )
{
    glVertex2f( x[i], y[i] );

}
glEnd();
Share:
12,039
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    I have the following code to draw an array of points but it only draws one point in the center. How can I draw an array of 2D points using OpenGL?

    GLint NumberOfPoints = 10;
    GLfloat x[2],y[2];
    
    glBegin( GL_POINTS );
    
    for ( int i = 0; i < NumberOfPoints; ++i )
    {
        glVertex2f( x[i], y[i] );
    
    }
    glEnd();