Search code examples
pythonopenglpyglet

pyglet drawing primitive GL_POINT. A buffer issue?


Beginner in pyglet. I have an issue when drawing GL_POINT using pyglet.graphicss.draw(). I want this GL_POINT to be drawn after another on the next pixel buffer, but it seems the function does not keep the last GL_POINT to be drawn on the next pixel buffer.

import pyglet
from pyglet.gl import *
from pyglet.window import key  # for key input, on_key_press

window = pyglet.window.Window(800, 600)  # create a window object with the resolution of 800x600
window.set_caption('window title')
glClear(GL_COLOR_BUFFER_BIT)
@window.event
def on_key_press(symbol, modifiers):  # keyboard input handler
    if symbol == key.L: # Drawing a center point
        print("DRAWING TEST A POINT (400, 300)")
        pyglet.graphics.draw(
            1, pyglet.gl.GL_POINTS,
            ('v2i', (400, 300))
        )

    elif symbol == key.K: # Drawing a bit further 100 more horizontally from center point
        print("DRAWING TEST A POINT (500, 300)")
        pyglet.graphics.draw(
            1, pyglet.gl.GL_POINTS,
            ('v2i', (500, 300))
        )

pyglet.app.run()

Pressing L would draw a center point.

Then pressing K would draw 100 more horizontally from the center point with the last center point gone.

Where is the bug? is there something wrong with my code? if not, my guess would be, does pyglet.graphicss.draw() function actually redraw one after another primitive shape? How do I code to draw one after another?


Solution

  • The issue is caused by Double buffering. You can solve the issue by drawing the point to both buffers. Draw the point twice and swap the OpenGL front and back buffers in between by (flip).

    pyglet.graphics.draw(
        1, pyglet.gl.GL_POINTS,
        ('v2i', (400, 300))
    )
    window.flip()
    pyglet.graphics.draw(
        1, pyglet.gl.GL_POINTS,
        ('v2i', (400, 300))
    )
    

    But I recommend to add the points to a list and to draw the list. e.g.:

    import pyglet
    from pyglet.gl import *
    from pyglet.window import key  # for key input, on_key_press
    
    points = []
    
    window = pyglet.window.Window(800, 600)  # create a window object with the resolution of 800x600
    window.set_caption('window title')
    glClear(GL_COLOR_BUFFER_BIT)
    @window.event
    def on_key_press(symbol, modifiers):  # keyboard input handler
        global points
        if symbol == key.L: # Drawing a center point
            print("DRAWING TEST A POINT (400, 300)")
            points += [400, 300]
    
        elif symbol == key.K: # Drawing a bit further 100 more horizontally from center point
            print("DRAWING TEST A POINT (500, 300)")
            points += [500, 300]
    
        pyglet.graphics.draw(len(points) // 2, pyglet.gl.GL_POINTS, ('v2i', points))
    
    pyglet.app.run()