Search code examples
pythonpython-3.xopenglpyopenglopengl-compat

How can I draw single 3D points?


I am using Python 3 with PyOpenGL and I need to draw single points in space. I know a point does not have volume, but I do not know if there is an easy way of drawing a point/sphere at certain coordinates. Edit: I am using opengl inside of pygame and inside a tkinter gui

I have tried the following code:

glEnable(GL_POINT_SMOOTH)
glBegin(GL_POINTS)
glColor3d(1, 1, 1)
glPointSize(200)
glVertex3d(1, 1, 1)
glEnd() # This throws an error

Error:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Program Files (x86)\Python37-32\lib\tkinter\__init__.py", line 1702, in __call__
    return self.func(*args)
  File "C:/Users/reas/Desktop/Programación/Dibujo/Dibujo.py", line 65, in vista_alzado
    glEnd()
  File "C:\Program Files (x86)\Python37-32\lib\site-packages\OpenGL\latebind.py", line 61, in __call__
    return self.wrapperFunction( self.baseFunction, *args, **named )
  File "C:\Program Files (x86)\Python37-32\lib\site-packages\OpenGL\GL\exceptional.py", line 45, in glEnd
    return baseFunction( )
  File "C:\Program Files (x86)\Python37-32\lib\site-packages\OpenGL\platform\baseplatform.py", line 409, in __call__
    return self( *args, **named )
  File "C:\Program Files (x86)\Python37-32\lib\site-packages\OpenGL\error.py", line 232, in glCheckError
    baseOperation = baseOperation,
OpenGL.error.GLError: GLError(
    err = 1282,
    description = b'operaci\xf3n no v\xe1lida',
    baseOperation = glEnd,
    cArguments = ()
)

Solution

  • The error is caused because glPointSize() is call with in a glBegin/glEnd sequence. This is not allowed.
    You've to call glPointSize before glBegin, e.g.:

    glEnable(GL_POINT_SMOOTH)
    glPointSize(5)
    
    glBegin(GL_POINTS)
    glColor3d(1, 1, 1)
    glVertex3d(0, 0, 0)
    glEnd()
    

    Once drawing of primitives was started by glBegin it is only allowed to specify vertex coordinates (glVertex) and change attributes (e.g. glColor, glTexCoord ...), till the drawn is ended (glEnd).
    All other instruction will be ignored and cause a GL_INVALID_OPERATION error (error code 1282).


    Note, if the model view matrix and the projection matrix is the identity matrix, then the coordinate (1, 1, 1) is the top, right (far) point of the viewport.
    The coordinate (0, 0, 0) would be in the center of the view (volume).

    Whereas if a perspective projection is used,

    gluPerspective(40, display[0]/display[1], 0.1, 50)
    

    then the z coordinate of the point has to be less than -near (near plane is 0.1 in the example) and grater than -far (far plane is 50) else the point is clipped by the near plane or far plane of the view frustum. Note the view space z-axis points out of the viewport. e.g.

    glVertex3d(0, 0, -1)
    

    See also Immediate mode and legacy OpenGL